PostgreSQL

@chat-adapter/state-pg

Production PostgreSQL state adapter for Chat SDK built with pg (node-postgres). Use this when PostgreSQL is your primary datastore and you want state persistence without a separate Redis dependency.

Installation

Usage

createPostgresState() auto-detects POSTGRES_URL (or DATABASE_URL) so you can call it with no arguments:

To provide a URL explicitly:

Using an existing client

Configuration

*Either url, POSTGRES_URL/DATABASE_URL, or client is required.

Environment variables

Data model

The adapter creates these tables automatically on connect():

All rows are namespaced by key_prefix.

Features

Locking considerations

The Redis state adapters use atomic SET NX PX for lock acquisition, which is a single atomic operation. The PostgreSQL adapter uses INSERT ... ON CONFLICT DO UPDATE WHERE expires_at <= now(), which relies on Postgres row-level locking. This is safe for most workloads but under extreme contention (many processes competing for the same lock simultaneously) may behave slightly differently than Redis. For high-contention distributed locking, prefer the Redis adapter.

Expired row cleanup

Unlike Redis (which handles TTL expiry natively), PostgreSQL does not automatically delete expired rows. The adapter performs opportunistic cleanup — expired locks are overwritten on the next acquireLock() call, and expired cache entries are deleted on the next get() call for that key.

For high-throughput deployments, you may want to run a periodic cleanup job:

License

MIT