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

# Database Persistence

> Persist agent conversations and state across sessions with 7 supported backends

Database persistence enables agents to maintain conversation history and application state across restarts, supporting production deployments and long-running applications.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Database Persistence Options"
        A[🧠 Agent] --> B[💬 Conversations]
        A --> C[🔄 State]
        B --> D[📊 SQL Stores]
        C --> E[🗃️ Key-Value Stores]
        D --> F[SQLite, PostgreSQL, MySQL]
        E --> G[Redis, MongoDB]
        A --> H[📁 JSON Files]
    end
    
    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef data fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef storage fill:#10B981,stroke:#7C90A0,color:#fff
    
    class A agent
    class B,C data
    class D,E,F,G,H storage
```

## Quick Start

<Steps>
  <Step title="Simple SQLite Setup">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, db

    agent = Agent(
        name="Assistant",
        instructions="You are a helpful assistant.",
        db=db(database_url="sqlite:///conversations.db"),
        session_id="my-session"
    )

    agent.chat("Hello!")  # Automatically persisted
    ```
  </Step>

  <Step title="Production PostgreSQL">
    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, db

    agent = Agent(
        name="Assistant", 
        instructions="You are a helpful assistant.",
        db=db(database_url="postgresql://user:pass@localhost/mydb"),
        session_id="production-session"
    )

    response = agent.chat("Remember my preferences")
    # Conversation automatically saved to PostgreSQL
    ```
  </Step>
</Steps>

***

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant DB as Database
    participant Store as Storage Backend
    
    User->>Agent: Send message
    Agent->>DB: Save message
    DB->>Store: Persist data
    Agent->>Agent: Process & respond
    Agent->>DB: Save response
    DB->>Store: Persist response
    Agent-->>User: Return response
    
    Note over User,Store: Session resume later...
    User->>Agent: New session
    Agent->>DB: Load history
    DB->>Store: Retrieve data
    Store-->>DB: Return history
    DB-->>Agent: Conversation context
```

| Component               | Purpose                           | Storage Type                              |
| ----------------------- | --------------------------------- | ----------------------------------------- |
| **ConversationStore**   | Messages, sessions, metadata      | SQL databases (SQLite, PostgreSQL, MySQL) |
| **StateStore**          | Application state, key-value data | NoSQL stores (Redis, MongoDB)             |
| **DefaultSessionStore** | File-based sessions               | JSON files on disk                        |

***

## Storage Backend Options

Choose the right backend for your use case:

<CardGroup cols={2}>
  <Card title="SQLite" icon="database" href="/docs/features/persistence-sqlite">
    Local file database - perfect for development and single-instance apps
  </Card>

  <Card title="PostgreSQL" icon="elephant" href="/docs/features/persistence-postgres">
    Production SQL database with advanced features and scalability
  </Card>

  <Card title="MySQL" icon="database" href="/docs/features/persistence-mysql">
    Popular SQL database with excellent tooling and ecosystem
  </Card>

  <Card title="Redis" icon="cubes-stacked" href="/docs/features/persistence-redis">
    Fast in-memory state store for high-performance applications
  </Card>

  <Card title="MongoDB" icon="leaf" href="/docs/features/persistence-mongodb">
    Flexible document store for complex state and metadata
  </Card>

  <Card title="ClickHouse" icon="chart-line" href="/docs/features/persistence-clickhouse">
    Analytics database for large-scale data processing
  </Card>

  <Card title="JSON Files" icon="file-code" href="/docs/features/persistence-json">
    Simple file-based storage with cross-platform locking — works on macOS, Linux, and Windows
  </Card>
</CardGroup>

***

## Common Patterns

### Multi-Backend Setup

Use different backends for conversations and state:

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

# SQL for conversations, Redis for state
agent = Agent(
    name="Assistant",
    db=db(
        database_url="postgresql://localhost/conversations",
        state_url="redis://localhost:6379"
    ),
    session_id="hybrid-session"
)
```

### Session Resume Workflow

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Initial session
agent = Agent(name="Assistant", db=db_instance, session_id="user-123")
agent.chat("My name is Alice")

# Later session - automatically resumes
agent2 = Agent(name="Assistant", db=db_instance, session_id="user-123") 
agent2.chat("What's my name?")  # Knows it's Alice
```

### Production Configuration

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

# Environment-based configuration
agent = Agent(
    name="ProdAssistant",
    db=db(
        database_url=os.getenv("DATABASE_URL"),
        state_url=os.getenv("REDIS_URL")
    ),
    session_id=f"user-{user_id}"
)
```

***

## Best Practices

<AccordionGroup>
  <Accordion title="Choose the Right Backend">
    * **SQLite**: Development, prototypes, single-user apps
    * **PostgreSQL/MySQL**: Multi-user production applications
    * **Redis**: High-frequency state updates, caching
    * **MongoDB**: Complex metadata, document storage
    * **JSON Files**: Simple scripts, minimal dependencies
  </Accordion>

  <Accordion title="Session Management">
    * Use meaningful session IDs (user-123, conversation-abc)
    * Consider session expiration for privacy compliance
    * Group related conversations under the same session
    * Clean up old sessions periodically
  </Accordion>

  <Accordion title="Error Handling">
    * Always handle database connection failures gracefully
    * Implement retry logic for transient network issues
    * Provide fallback to in-memory storage if database unavailable
    * Monitor database performance and connection pools
  </Accordion>

  <Accordion title="Performance Optimization">
    * Use connection pooling for production deployments
    * Configure appropriate timeouts for your use case
    * Consider read replicas for high-read workloads
    * Monitor database metrics and query performance
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="Session Management" icon="clock" href="/docs/concepts/session-management">
    Learn about session lifecycle and management
  </Card>

  <Card title="Memory vs Context" icon="brain" href="/docs/concepts/memory-vs-learning">
    Understand the difference between persistence and memory
  </Card>
</CardGroup>
