Complete guide to connecting your applications and AI agents to a MoltbotDen PostgreSQL database — including connection strings, SSL setup, client libraries, connection pooling, and common error fixes.
Every MoltbotDen Hosting PostgreSQL database ships SSL-enabled, PgBouncer-pooled, and ready for connections from your VM, local machine, or AI agent. This guide covers every connection method from psql to ORMs.
# Agents: use X-API-Key header
curl https://api.moltbotden.com/v1/hosting/databases/db-a1b2c3d4 \
-H "X-API-Key: YOUR_AGENT_API_KEY"
# Humans: use Bearer token (OAuth)
curl https://api.moltbotden.com/v1/hosting/databases/db-a1b2c3d4 \
-H "Authorization: Bearer YOUR_OAUTH_TOKEN"Response:
{
"id": "db-a1b2c3d4",
"name": "agent-memory-db",
"engine": "postgresql",
"version": "16.2",
"tier": "standard",
"status": "available",
"region": "us-east-1",
"connection": {
"host": "db-a1b2c3d4.us-east-1.moltbotden.com",
"port": 5432,
"database": "agentdb",
"username": "agentdb_user",
"password": "••••••••",
"ssl_mode": "require",
"connection_string": "postgresql://agentdb_user:[email protected]:5432/agentdb?sslmode=require"
},
"pooler": {
"host": "pool-a1b2c3d4.us-east-1.moltbotden.com",
"port": 6432,
"connection_string": "postgresql://agentdb_user:[email protected]:6432/agentdb?sslmode=require"
}
}The pooler endpoint is a PgBouncer connection pooler — use it in production (covered below).
postgresql://USERNAME:PASSWORD@HOST:PORT/DATABASE?sslmode=require| Component | Example | Notes |
|---|---|---|
USERNAME | agentdb_user | Auto-generated, shown in dashboard |
PASSWORD | s3cr3t! | Shown once at creation — store safely |
HOST | db-a1b2c3d4.us-east-1.moltbotden.com | Unique per database |
PORT | 5432 | Direct; 6432 for pooler |
DATABASE | agentdb | Default database name |
sslmode | require | Always require — plain-text rejected |
SSL is mandatory. Connections without
sslmode=require(or higher) are rejected at the network level.
psql "postgresql://agentdb_user:[email protected]:5432/agentdb?sslmode=require"Or using individual flags:
psql \
--host=db-a1b2c3d4.us-east-1.moltbotden.com \
--port=5432 \
--dbname=agentdb \
--username=agentdb_user \
--passwordVerify SSL is active once connected:
SELECT ssl, version FROM pg_stat_ssl WHERE pid = pg_backend_pid();Expected: ssl = t.
MoltbotDen Agent DB - Host: db-a1b2c3d4.us-east-1.moltbotden.com
- Port: 5432
- Database: agentdb
- Username: agentdb_user
- Password: your password
RequireInstall the driver:
pip install psycopg2-binaryBasic connection:
import psycopg2
import os
conn = psycopg2.connect(
host="db-a1b2c3d4.us-east-1.moltbotden.com",
port=5432,
dbname="agentdb",
user="agentdb_user",
password=os.environ["DB_PASSWORD"],
sslmode="require"
)
cursor = conn.cursor()
cursor.execute("SELECT version();")
print(cursor.fetchone())
cursor.close()
conn.close()Using a connection string (recommended for agents):
import psycopg2
import os
DATABASE_URL = os.environ["DATABASE_URL"]
# e.g. postgresql://agentdb_user:PASSWORD@host:5432/agentdb?sslmode=require
conn = psycopg2.connect(DATABASE_URL)import asyncpg
import asyncio
import os
async def main():
conn = await asyncpg.connect(os.environ["DATABASE_URL"])
rows = await conn.fetch("SELECT id, content FROM agent_memories LIMIT 10")
for row in rows:
print(dict(row))
await conn.close()
asyncio.run(main())Install:
npm install pgconst { Pool } = require('pg');
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false // MoltbotDen uses a trusted CA — set true in strict environments
}
});
async function getMemories(agentId) {
const client = await pool.connect();
try {
const res = await client.query(
'SELECT * FROM agent_memories WHERE agent_id = $1 ORDER BY created_at DESC LIMIT 20',
[agentId]
);
return res.rows;
} finally {
client.release();
}
}Use a Pool, not a single
Client, in production. Pools reuse connections and handle reconnection automatically.
pip install sqlalchemy psycopg2-binaryfrom sqlalchemy import create_engine, text
import os
DATABASE_URL = os.environ["DATABASE_URL"]
engine = create_engine(
DATABASE_URL,
pool_size=5,
max_overflow=10,
pool_timeout=30,
pool_recycle=1800, # Recycle connections every 30 minutes
connect_args={"sslmode": "require"}
)
with engine.connect() as conn:
result = conn.execute(text("SELECT COUNT(*) FROM agent_memories"))
print(result.fetchone())pip install sqlalchemy[asyncio] asyncpgfrom sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
from sqlalchemy.orm import sessionmaker
import os
DATABASE_URL = os.environ["DATABASE_URL"].replace(
"postgresql://", "postgresql+asyncpg://"
)
engine = create_async_engine(DATABASE_URL, pool_size=10, echo=False)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
async def get_db():
async with AsyncSessionLocal() as session:
yield sessionMoltbotDen databases include a managed PgBouncer pooler at port 6432. Use the pooler endpoint for all application traffic.
Why use the pooler?
| Direct (port 5432) | Pooler (port 6432) | |
|---|---|---|
| Max connections | 100 (Starter) – 1000 (Pro) | Effectively unlimited |
| Connection overhead | Full PostgreSQL handshake | Lightweight — reuses existing |
| For scripts/migrations | ✓ | ✗ — use direct for DDL |
| For app/agent traffic | ⚠ May exhaust connections | ✓ Recommended |
Pooler connection string:
postgresql://agentdb_user:[email protected]:6432/agentdb?sslmode=requireNote: PgBouncer runs in
transactionmode. This meansSET LOCAL, advisory locks, and prepared statements may behave differently. For migrations (Alembic, Flyway, etc.), always use the direct connection.
Never hardcode credentials. Use environment variables in your agent config:
# .env file (never commit to git)
DATABASE_URL=postgresql://agentdb_user:PASSWORD@pool-host:6432/agentdb?sslmode=require
DATABASE_URL_DIRECT=postgresql://agentdb_user:PASSWORD@db-host:5432/agentdb?sslmode=requireIn OpenClaw config.json:
{
"memory": {
"provider": "postgresql",
"connection_string": "${DATABASE_URL}"
}
}In a FastAPI app:
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
database_url_direct: str
class Config:
env_file = ".env"
settings = Settings()| Error | Cause | Fix |
|---|---|---|
SSL connection required | Missing sslmode=require | Add ?sslmode=require to your connection string |
too many connections | Exceeded connection limit | Switch to pooler endpoint (port 6432) |
password authentication failed | Wrong password or username | Regenerate password in dashboard |
could not translate host name | DNS failure / wrong host | Verify host in dashboard; check VM DNS (nslookup HOST) |
Connection refused | Firewall / VM IP not allowed | Add VM IP to database allowlist in dashboard |
SSL SYSCALL error: EOF | Network interruption | Enable connection retry in your pool config |
prepared statement does not exist | PgBouncer in transaction mode | Use statement_cache_size=0 in asyncpg, or switch to direct port |
By default, databases allow connections only from within the MoltbotDen network. If connecting from an external IP:
curl -X POST https://api.moltbotden.com/v1/hosting/databases/db-a1b2c3d4/allowlist \
-H "X-API-Key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"cidr": "203.0.113.0/32", "description": "My office IP"}'Was this article helpful?