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

# Use PostgreSQL storage

The `postgresql` backend stores sessions in a PostgreSQL database. Multiple agent instances can connect to the same database for shared, distributed persistence.

## When to use

* Production, multi-instance, or distributed deployments;
* Teams already using PostgreSQL as shared storage.

## Prerequisites

The `veadk-python` installation includes the required database drivers. Before running the example, create the database and account, grant permissions to create and read/write session tables, and make the database reachable. VeADK does not provision the database service or database itself

Provide connection settings through environment variables and inject the password from your deployment secret configuration

```bash theme={null}
export DATABASE_POSTGRESQL_HOST="127.0.0.1"
export DATABASE_POSTGRESQL_USER="veadk"
export DATABASE_POSTGRESQL_DATABASE="veadk_sessions"
```

Also set `DATABASE_POSTGRESQL_PASSWORD`. These settings work with reachable self-managed, Volcengine, or BytePlus database instances; they do not automatically select a cloud provider or region

## Usage

Provide connection details via `config.yaml` (or the matching environment variables) — never hard-code the password.

```python lines theme={null}
import asyncio

from veadk.memory.short_term_memory import ShortTermMemory

stm = ShortTermMemory(backend="postgresql")

async def main():
    try:
        await stm.create_session(
            app_name="memory_demo", user_id="user_42", session_id="chat_01"
        )
        session = await stm.session_service.get_session(
            app_name="memory_demo", user_id="user_42", session_id="chat_01"
        )
        assert session is not None
        print(session.id)
    finally:
        await stm.session_service.close()

asyncio.run(main())
```

The output is `chat_01`, confirming that the session was created and read back. This example does not call a model. For conversations, pass the same `stm` to `Runner(short_term_memory=stm, agent=agent)` and keep the app, user, and session identifiers consistent

To forward SQLAlchemy driver args such as connection pooling, use `db_kwargs`:

```python lines theme={null}
stm = ShortTermMemory(
    backend="postgresql",
    db_kwargs={"pool_size": 10, "pool_recycle": 3600},
)
```

You can also inject a `PostgreSqlConfig` directly through `backend_configs` to override the environment variables:

```python lines theme={null}
import os

from veadk.configs.database_configs import PostgreSqlConfig

stm = ShortTermMemory(
    backend="postgresql",
    backend_configs={
        "postgresql_config": PostgreSqlConfig(
            host="127.0.0.1",
            port=5432,
            user="veadk",
            password=os.environ["DATABASE_POSTGRESQL_PASSWORD"],
            database="veadk_sessions",
            schema="support_agent",
        )
    },
)
```

## Parameters

### ShortTermMemory constructor parameters (postgresql)

| Parameter | Type | Default | Effective for postgresql | Description |
| :- | :- | :- | :- | :- |
| `backend` | `str` | `"local"` | Yes | Set to `"postgresql"` to select this backend. |
| `backend_configs` | `dict` | `{}` | Yes | PostgreSQL-specific settings; may include `postgresql_config` (a `PostgreSqlConfig` instance) to override the configuration otherwise read from environment variables. |
| `db_kwargs` | `dict` | `{}` | Yes | Passed to the SQLAlchemy engine; commonly used for pool settings such as `pool_size`, `pool_recycle`, `pool_pre_ping`. |
| `db_url` | `str` | `""` | Yes (override) | A connection string. Once set, `backend` and `backend_configs` are ignored, and `db_url` is used with `db_kwargs`. |
| `local_database_path` | `str` | `/tmp/veadk_local_database.db` | No | Used only by `sqlite`. |
| `after_load_memory_callback` | `Callable \| None` | `None` | Yes | Synchronous read callback; receives `Session` or `None` plus the query arguments. Use `def callback(session, *args, **kwargs)` |
| `after_create_session_callback` | `Callable \| None` | `None` | Yes | Runs after `ShortTermMemory.create_session()` creates a new session; accepts the new `Session` and can be synchronous or asynchronous |

### PostgreSqlConfig fields and environment variables

The `PostgreSqlConfig` config class uses the env prefix `DATABASE_POSTGRESQL_`.

```yaml config.yaml lines theme={null}
database:
  postgresql:
    host:       # host or IP
    port: 5432
    user:
    password:
    database:
    schema: support_agent
```

| Field | Env var | Type | Default | Description |
| :- | :- | :- | :- | :- |
| `host` | `DATABASE_POSTGRESQL_HOST` | `str` | `""` | Database host or IP. |
| `port` | `DATABASE_POSTGRESQL_PORT` | `int` | `5432` | Port. |
| `user` | `DATABASE_POSTGRESQL_USER` | `str` | `""` | Username. |
| `password` | `DATABASE_POSTGRESQL_PASSWORD` | `str` | `""` | Password. |
| `database` | `DATABASE_POSTGRESQL_DATABASE` | `str` | `""` | Database name. |
| `schema` | `DATABASE_POSTGRESQL_SCHEMA` | `str` | `""` | Optional PostgreSQL schema. VeADK creates it when needed during connection and keeps session tables inside it; the account needs the corresponding schema creation and usage permissions |
| `secret_token` | `DATABASE_POSTGRESQL_SECRET_TOKEN` | `str` | `""` | STS token for PostgreSQL auth; not supported yet. |

<Note>
  VeADK selects a PostgreSQL driver compatible with the installed Google ADK version and automatically encodes special characters in usernames and passwords. You can [provision PostgreSQL on Volcengine](https://www.volcengine.com/product/rds-pg).
</Note>

Use `schema` when several VeADK deployments share a database but must keep separate session tables. Schema names may contain letters, digits, and underscores and cannot start with a digit.
