Skip to main content
The PostgresDb class provides PostgreSQL storage for agents, sessions, memories, and more. It’s the recommended database for production deployments.

Constructor

from agno.db.postgres import PostgresDb

db = PostgresDb(
    host="localhost",
    port=5432,
    db="agno",
    user="user",
    password="password"
)

Parameters

host
str
default:"localhost"
PostgreSQL server host.
port
int
default:"5432"
PostgreSQL server port.
db
str
required
Database name.
user
str
required
Database user.
password
str
required
Database password.
driver
str
default:"psycopg"
Database driver: “psycopg” or “pg8000”.
pool_size
int
default:"5"
Connection pool size.
max_overflow
int
default:"10"
Maximum overflow connections.
create_tables
bool
default:"True"
If True, automatically creates required tables.
session_table
str
default:"agno_sessions"
Name of the sessions table.
And other table name parameters.

Methods

Inherits all methods from BaseDb.

close()

Close database connections and release pool resources.
db.close()

Example Usage

from agno import Agent
from agno.db.postgres import PostgresDb

db = PostgresDb(
    host="localhost",
    db="agno",
    user="agno_user",
    password="secret"
)

agent = Agent(
    model="gpt-4o",
    db=db,
    add_history_to_context=True
)

Production Setup

Connection String

from agno.db.postgres import PostgresDb

db = PostgresDb.from_url(
    "postgresql://user:password@localhost:5432/agno"
)

With Connection Pooling

db = PostgresDb(
    host="db.example.com",
    db="agno",
    user="app_user",
    password="secret",
    pool_size=20,        # Core pool size
    max_overflow=30,     # Additional connections
    pool_timeout=30,     # Wait time for connection
    pool_recycle=3600    # Recycle connections after 1 hour
)

Multi-tenancy

# Separate tables per tenant
tenant_db = PostgresDb(
    host="localhost",
    db="agno",
    user="user",
    password="password",
    session_table=f"tenant_{tenant_id}_sessions",
    memory_table=f"tenant_{tenant_id}_memories"
)

Best Practices

  1. Use connection pooling: Configure appropriate pool_size for your workload
  2. Environment variables: Store credentials in environment variables
  3. SSL in production: Always use SSL for production databases
  4. Regular backups: Set up automated backups
  5. Monitor connections: Monitor pool usage and adjust as needed
  6. Close on shutdown: Call db.close() during application shutdown
  7. Indexes: Ensure tables are properly indexed for your queries

Migration from SQLite

from agno.db.sqlite import SQLiteDb
from agno.db.postgres import PostgresDb

# Export from SQLite
sqlite_db = SQLiteDb(db_file="agent.db")
sessions = sqlite_db.get_sessions(session_type=SessionType.AGENT)

# Import to PostgreSQL
postgres_db = PostgresDb(...)
postgres_db.upsert_sessions(sessions)

Build docs developers (and LLMs) love