> ## Documentation Index
> Fetch the complete documentation index at: https://praison.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Redis State Store

> High-performance in-memory state storage for fast agent data access

Redis stores agent state in memory for sub-millisecond access — pair it with a SQL backend for conversation history.

<Note>
  This is the supported way to use Redis with PraisonAI. `MemoryConfig(backend="redis")` is no longer accepted — it raises a `ValueError`. Always attach Redis through `db(state_url=...)` as shown below.
</Note>

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, MemoryConfig
from praisonaiagents import db

agent = Agent(
    name="FastBot",
    instructions="You are a helpful assistant.",
    memory=MemoryConfig(
        db=db(state_url="redis://localhost:6379"),
        session_id="redis-session",
    ))
agent.start("Store my preferences in Redis")
```

The user updates session state; Redis serves fast reads while SQL can hold conversation history.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    Agent[🤖 Agent] --> Store[📦 Redis State]
    Store --> Adapter[⚡ RedisStorageAdapter]
    Adapter --> Redis[(Redis)]

    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef store fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef redis fill:#10B981,stroke:#7C90A0,color:#fff

    class Agent agent
    class Store,Adapter store
    class Redis redis
```

## Quick Start

<Steps>
  <Step title="Simple Usage">
    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    pip install redis praisonai
    ```

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, MemoryConfig
    from praisonaiagents import db

    agent = Agent(
        name="FastBot",
        memory=MemoryConfig(
            db=db(state_url="redis://localhost:6379"),
            session_id="session-1",
        ))
    agent.start("Hello!")
    ```
  </Step>

  <Step title="With Configuration">
    Hybrid setup — SQL for conversations, Redis for state:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, MemoryConfig
    from praisonaiagents import db

    agent = Agent(
        name="HybridBot",
        memory=MemoryConfig(
            db=db(
                database_url="postgresql://user:pass@localhost/conversations",
                state_url="redis://localhost:6379",
            ),
            session_id="hybrid-session",
        ))
    agent.start("Conversations in Postgres, state in Redis")
    ```
  </Step>
</Steps>

***

## How It Works

Redis is a **state store** — fast key-value access for agent preferences and runtime data. Conversation history uses `database_url` separately.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant Agent
    participant Store as RedisStateStore
    participant Redis

    Agent->>Store: set(key, value, ttl?)
    Store->>Redis: SET praison:key
    Agent->>Store: get(key)
    Redis-->>Agent: value
```

| Feature             | Description                                       |
| ------------------- | ------------------------------------------------- |
| **In-memory speed** | Sub-millisecond reads and writes                  |
| **TTL support**     | Expire keys automatically with `ttl`              |
| **Key prefix**      | Namespace keys with `prefix` (default `praison:`) |

***

## Configuration Options

| Option             | Type   | Default       | Description                                      |
| ------------------ | ------ | ------------- | ------------------------------------------------ |
| `url`              | `str`  | `None`        | Full Redis URL (overrides host/port/db/password) |
| `host`             | `str`  | `"localhost"` | Redis host when `url` is not set                 |
| `port`             | `int`  | `6379`        | Redis port                                       |
| `db`               | `int`  | `0`           | Redis database number                            |
| `password`         | `str`  | `None`        | Redis password                                   |
| `prefix`           | `str`  | `"praison:"`  | Key prefix for namespacing                       |
| `decode_responses` | `bool` | `True`        | Compatibility flag (not used internally)         |
| `socket_timeout`   | `int`  | `5`           | Socket timeout in seconds                        |
| `max_connections`  | `int`  | `10`          | Compatibility flag for pool size                 |

### URL formats

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
db(state_url="redis://localhost:6379")
db(state_url="redis://:password@host:6379/0")
```

***

## Production notes

Redis is single-threaded, so a slow admin command stalls every other client on the same instance. To list many keys, call `scan_prefix()` instead of `keys()` — it walks the keyspace with a non-blocking cursor `SCAN` (batches of `500`) so a large read never freezes agents sharing the instance.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai.persistence import create_state_store

store = create_state_store("redis", url="redis://localhost:6379")

recent = store.scan_prefix("session:")
```

| Method                      | Under the hood                | Safe on large keyspaces |
| --------------------------- | ----------------------------- | ----------------------- |
| `store.keys(pattern)`       | Redis `KEYS` (O(N), blocking) | Small keyspaces only    |
| `store.scan_prefix(prefix)` | `SCAN` cursor (batch `500`)   | ✅                       |

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant Agent
    participant Store as RedisStateStore
    participant Redis

    Agent->>Store: scan_prefix("session:")
    loop batched cursor scan
        Store->>Redis: SCAN cursor MATCH session:* COUNT 500
        Redis-->>Store: cursor, chunk
    end
    Store-->>Agent: keys[]
```

***

## Best Practices

<AccordionGroup>
  <Accordion title="Prefer scan_prefix() for large listings">
    `scan_prefix(prefix)` uses a non-blocking `SCAN` cursor (batch `500`), so admin or garbage-collection reads on a large keyspace never stall other agents sharing the Redis instance. Reserve `keys(pattern)` for small keyspaces.
  </Accordion>

  <Accordion title="Pair Redis with a SQL conversation backend">
    Use `database_url` for chat history and `state_url` for fast ephemeral state.
  </Accordion>

  <Accordion title="Set TTL on ephemeral keys">
    Pass `ttl` when storing session-scoped data that should expire automatically.
  </Accordion>

  <Accordion title="Use a key prefix per environment">
    Set `prefix="prod:"` vs `prefix="staging:"` to isolate keys on a shared Redis instance.
  </Accordion>

  <Accordion title="Enable persistence for durability">
    Configure Redis AOF or RDB snapshots if state must survive Redis restarts.
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="MongoDB State Store" icon="leaf" href="/docs/features/persistence-mongodb">
    Document-based state with flexible schemas
  </Card>

  <Card title="Database Persistence" icon="database" href="/docs/features/persistence">
    Overview of conversation and state backends
  </Card>
</CardGroup>
