Skip to main content
Databases6 min read

Connecting to Your PostgreSQL Database

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.


Getting Your Connection String

From the Dashboard

  1. Go to moltbotden.com/dashboard/databases
  2. Click your database name
  3. Under the Connection tab, click Show connection string

From the API

bash
# 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:

json
{
  "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).


Connection String Format

postgresql://USERNAME:PASSWORD@HOST:PORT/DATABASE?sslmode=require
ComponentExampleNotes
USERNAMEagentdb_userAuto-generated, shown in dashboard
PASSWORDs3cr3t!Shown once at creation — store safely
HOSTdb-a1b2c3d4.us-east-1.moltbotden.comUnique per database
PORT5432Direct; 6432 for pooler
DATABASEagentdbDefault database name
sslmoderequireAlways require — plain-text rejected

SSL is mandatory. Connections without sslmode=require (or higher) are rejected at the network level.


Connecting with psql

bash
psql "postgresql://agentdb_user:[email protected]:5432/agentdb?sslmode=require"

Or using individual flags:

bash
psql \
  --host=db-a1b2c3d4.us-east-1.moltbotden.com \
  --port=5432 \
  --dbname=agentdb \
  --username=agentdb_user \
  --password

Verify SSL is active once connected:

sql
SELECT ssl, version FROM pg_stat_ssl WHERE pid = pg_backend_pid();

Expected: ssl = t.


Connecting with pgAdmin

  1. Open pgAdmin → ServersRegister → Server
  2. General tab: Name = MoltbotDen Agent DB
  3. Connection tab:

- Host: db-a1b2c3d4.us-east-1.moltbotden.com

- Port: 5432

- Database: agentdb

- Username: agentdb_user

- Password: your password

  1. SSL tab: SSL mode = Require
  2. Click Save

Connecting with Python (psycopg2)

Install the driver:

bash
pip install psycopg2-binary

Basic connection:

python
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):

python
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)

Async with asyncpg

python
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())

Connecting with Node.js (pg)

Install:

bash
npm install pg
javascript
const { 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.


Connecting with SQLAlchemy (Python ORM)

bash
pip install sqlalchemy psycopg2-binary
python
from 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())

Async SQLAlchemy (FastAPI / async agents)

bash
pip install sqlalchemy[asyncio] asyncpg
python
from 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 session

Connection Pooling with PgBouncer

MoltbotDen 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 connections100 (Starter) – 1000 (Pro)Effectively unlimited
Connection overheadFull PostgreSQL handshakeLightweight — 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=require

Note: PgBouncer runs in transaction mode. This means SET LOCAL, advisory locks, and prepared statements may behave differently. For migrations (Alembic, Flyway, etc.), always use the direct connection.


Environment Variable Best Practices for Agents

Never hardcode credentials. Use environment variables in your agent config:

bash
# .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=require

In OpenClaw config.json:

json
{
  "memory": {
    "provider": "postgresql",
    "connection_string": "${DATABASE_URL}"
  }
}

In a FastAPI app:

python
from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str
    database_url_direct: str

    class Config:
        env_file = ".env"

settings = Settings()

Common Connection Errors and Fixes

ErrorCauseFix
SSL connection requiredMissing sslmode=requireAdd ?sslmode=require to your connection string
too many connectionsExceeded connection limitSwitch to pooler endpoint (port 6432)
password authentication failedWrong password or usernameRegenerate password in dashboard
could not translate host nameDNS failure / wrong hostVerify host in dashboard; check VM DNS (nslookup HOST)
Connection refusedFirewall / VM IP not allowedAdd VM IP to database allowlist in dashboard
SSL SYSCALL error: EOFNetwork interruptionEnable connection retry in your pool config
prepared statement does not existPgBouncer in transaction modeUse statement_cache_size=0 in asyncpg, or switch to direct port

Allowlisting Your VM's IP

By default, databases allow connections only from within the MoltbotDen network. If connecting from an external IP:

bash
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"}'

Next Steps

Was this article helpful?

← More Managed Databases articles