DocsGet started
View as MarkdownConnecting
Connection strings, region hostnames, direct, pooled and read-only hosts, TLS, query cancellation, driver examples, connection limits and waking a sleeping database.
Every KeelDB database is reachable on port 5432 through three hostnames built from its database id and its region. All connections use TLS.
Connection strings
Get the connection details from the database's Overview page in the console, from GET /api/v1/databases/{id}/connection, or from the get_connection_string MCP tool. Each of these reveals the password and is recorded in the audit log.
# Direct
postgresql://shop_owner:<password>@k7m2x9qa4pz1.us-east.db.keeldb.com:5432/shop?sslmode=require&connect_timeout=10
# Pooled
postgresql://shop_owner:<password>@k7m2x9qa4pz1-pooler.us-east.db.keeldb.com:5432/shop?sslmode=require&connect_timeout=10| Field | Value |
|---|---|
| User | <database>_owner. It owns the database and can read all statistics views, but it is not a superuser. |
| Password | 32 random letters and digits, so it never needs URL encoding. |
| Database | Derived from the database name you chose (lowercase letters, digits and underscores). |
| Host | <id>[-pooler or -ro].<region>.db.keeldb.com, see below. |
| Port | 5432 on every host. |
The examples below assume two environment variables: DATABASE_URL holds the pooled URI and DIRECT_URL holds the direct URI.
Regions and hostnames
Each database lives in one region, and its hostnames name that region:
| Region | Centered on | Hostnames |
|---|---|---|
US East (us-east) | Ashburn, Virginia | <id>.us-east.db.keeldb.com, <id>-pooler.us-east.db.keeldb.com, <id>-ro.us-east.db.keeldb.com |
Where databases run in US East:
| What | Where |
|---|---|
| Free and Launch databases | Our shared server at AWS in Northern Virginia (AWS's US East region), with more servers there when we need room. If the shared server is lost, a replacement of the same kind, normally in another availability zone of Northern Virginia, takes over, restored from backups |
| Dedicated databases | Servers of their own at AWS in Northern Virginia, in two availability zones (separate data centers), or reserved capacity on our shared server there until Dedicated servers open |
| Connection proxies, console and API | Ashburn, Virginia (Hetzner), which serves all traffic while it is healthy, with a live copy in Piscataway, New Jersey (Vultr) that takes over within minutes if Ashburn is unreachable or cut off |
KeelDB's six regions are US East (us-east-1, Northern Virginia), US West (us-west-2, Oregon), Europe (eu-central-1, Frankfurt), UK (eu-west-2, London), Asia (ap-southeast-1, Singapore) and Middle East (me-central-1, UAE), each with its own hostnames. A database keeps its hostnames for its whole life: when it fails over, is restored onto another server or into another data center of its region, or moves between plans, the hostname stays the same and starts pointing at the new primary.
Each hostname resolves to the region's connection proxies, normally the ones in Ashburn, next to where most databases run, with the proxies in Piscataway as a fallback, and the answer can contain several addresses. libpq and most drivers try every returned address in turn, so a connection moves on when one proxy is unreachable. That is why the connection strings include connect_timeout=10: an unreachable proxy costs at most 10 seconds before the next address is tried. Keep it, or set a similar timeout in your driver. Our DNS answers are short-lived (30 seconds), so a client that resolves the name again on reconnect follows a change quickly.
Choose a host
| Host | Routes to | Use it for |
|---|---|---|
<id>.<region>.db.keeldb.com | The primary, read-write | Migrations and schema changes, LISTEN/NOTIFY, session features (advisory locks, temporary tables, SET), long-running app servers with their own pool, pg_dump and pg_restore |
<id>-pooler.<region>.db.keeldb.com | PgBouncer in transaction mode, in front of the primary | Serverless and edge functions, many short-lived connections, apps with many processes |
<id>-ro.<region>.db.keeldb.com | Read-only copies | Reporting, analytics and read scaling |
Notes:
- The pooler is on by default. If you turn it off (database Settings, or
pooler_enabled: falsein the API), the-poolerhost connects straight to the primary. - The
-rohost exists when the database has more than one copy: on Launch or Dedicatedsingleonce you add a read replica, and always on Dedicatedha2andha3where they are offered (it serves reads from the standbys; US East does not offer them yet). Without one, connections to-rofail withthis database has no read replicas. On a new database or branch, or after you add the first replica,-rostarts serving once the standby or replica is up, usually a minute or two later. Until then, connections to-rofail with SQLSTATE57P03and a message such asthe standby of this database is startingorthe read replica of this database is starting: retry in a minute, or use the primary host meanwhile. - Read-only copies replicate from the primary, so a row you just wrote may not be visible there yet. See High availability for how
ha2standbys replicate whereha2is offered.
Transaction mode caveats
In transaction mode, PgBouncer assigns a server connection to your client for one transaction at a time. Two consecutive transactions from the same client can run on different server connections, so anything that lives in the session is unreliable through the -pooler host:
SEToutside a transaction. UseSET LOCALinside the transaction instead, or set defaults withALTER DATABASE ... SETorALTER ROLE ... SET.- Session advisory locks (
pg_advisory_lock). Usepg_advisory_xact_lock, or connect directly. LISTEN, temporary tables kept across transactions, andWITH HOLDcursors. Use the direct host.- Prepared statements: protocol-level prepared statements, the kind drivers create, are supported. PgBouncer is configured with
max_prepared_statements = 200. SQL-levelPREPARE,EXECUTEandDEALLOCATEare not supported through the pooler.
Every host applies idle_in_transaction_session_timeout = 10min: a session left idle inside an open transaction for 10 minutes is terminated.
TLS
TLS is required. Use sslmode=require (the connection strings already include it). The proxy refuses plaintext connections with the error KeelDB requires TLS: connect with sslmode=require.
TLS 1.2 or newer is accepted. TLS ends at the KeelDB proxy, so leave channel_binding at its default (prefer): logins use SCRAM without channel binding, and channel_binding=require is refused. From the proxy, your connection travels to your database over our cluster's private network, which is encrypted with WireGuard between servers.
Clients on libpq 17 or newer can skip one round trip with PostgreSQL 17 direct TLS by adding sslnegotiation=direct:
psql "postgresql://shop_owner:<password>@k7m2x9qa4pz1.us-east.db.keeldb.com:5432/shop?sslmode=require&sslnegotiation=direct"Cancelling queries
Query cancellation (Ctrl+C in psql, or your driver's cancel call) works through any of our proxies. A driver sends a cancel on a new connection, which DNS may send to a different proxy than the one running your query; that proxy passes the cancel on to the right one, so the query is cancelled either way.
The process id your driver reports for a connection is a KeelDB connection id, not the server's pg_backend_pid(). To cancel or end a session from SQL with pg_cancel_backend() or pg_terminate_backend(), take its pid from pg_stat_activity.
Examples
psql
psql "$DIRECT_URL"Node.js with node-postgres
import pg from "pg";
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
const { rows } = await pool.query("select now()");
console.log(rows[0]);Node.js with postgres.js
import postgres from "postgres";
const sql = postgres(process.env.DATABASE_URL, { ssl: "require" });
const [row] = await sql`select now()`;
console.log(row);Prisma
Point the app at the pooler and give Prisma Migrate a direct connection:
DATABASE_URL="postgresql://shop_owner:<password>@k7m2x9qa4pz1-pooler.us-east.db.keeldb.com:5432/shop?sslmode=require&pgbouncer=true"
DIRECT_URL="postgresql://shop_owner:<password>@k7m2x9qa4pz1.us-east.db.keeldb.com:5432/shop?sslmode=require"datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}This is the Prisma 6 schema syntax. With Prisma 7, set the CLI connection in prisma.config.ts to DIRECT_URL, and pass DATABASE_URL to the @prisma/adapter-pg driver adapter in your app.
import { defineConfig, env } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
datasource: { url: env("DIRECT_URL") },
});import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "./generated/prisma/client"; // your generator's output path
const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL });
export const prisma = new PrismaClient({ adapter });Drizzle
// src/db/index.ts
import { drizzle } from "drizzle-orm/node-postgres";
export const db = drizzle(process.env.DATABASE_URL!);// drizzle.config.ts: drizzle-kit runs migrations over the direct host
import { defineConfig } from "drizzle-kit";
export default defineConfig({
dialect: "postgresql",
schema: "./src/db/schema.ts",
dbCredentials: { url: process.env.DIRECT_URL! },
});Python with psycopg 3
import os
import psycopg
# prepare_threshold=None turns off psycopg's automatic server-side prepares,
# which is the safe setting on the -pooler host.
with psycopg.connect(os.environ["DATABASE_URL"], prepare_threshold=None) as conn:
print(conn.execute("select now()").fetchone())Python with SQLAlchemy
import os
from sqlalchemy import create_engine, text
url = os.environ["DATABASE_URL"].replace("postgresql://", "postgresql+psycopg://", 1)
engine = create_engine(url, pool_pre_ping=True, connect_args={"prepare_threshold": None})
with engine.connect() as conn:
print(conn.execute(text("select now()")).scalar())Go with pgx
package main
import (
"context"
"fmt"
"os"
"github.com/jackc/pgx/v5/pgxpool"
)
func main() {
ctx := context.Background()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
panic(err)
}
defer pool.Close()
var now string
if err := pool.QueryRow(ctx, "select now()::text").Scan(&now); err != nil {
panic(err)
}
fmt.Println(now)
}pgx caches prepared statements by default, which the pooler supports. If you see prepared statement ... does not exist errors through the pooler, add default_query_exec_mode=exec to the connection string.
Ruby on Rails
Rails reads DATABASE_URL automatically. Run the app on the pooler and turn off the features that need a session:
# config/database.yml
production:
adapter: postgresql
url: <%= ENV["DATABASE_URL"] %>
prepared_statements: false
advisory_locks: falseRun migrations over the direct host, where advisory locks work:
DATABASE_URL="$DIRECT_URL" bin/rails db:migrateDjango
# settings.py
import os
from urllib.parse import unquote, urlparse
url = urlparse(os.environ["DATABASE_URL"])
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": url.path.lstrip("/"),
"USER": unquote(url.username),
"PASSWORD": unquote(url.password),
"HOST": url.hostname,
"PORT": url.port or 5432,
"OPTIONS": {"sslmode": "require"},
"CONN_MAX_AGE": 60,
# Needed when DATABASE_URL points at the -pooler host (transaction mode).
"DISABLE_SERVER_SIDE_CURSORS": True,
}
}Run manage.py migrate with DATABASE_URL set to the direct URI.
Clients without SNI
KeelDB routes each connection by the hostname the client sends during the TLS handshake (SNI). libpq before version 14 and some drivers don't send it. For those clients, name the database in the options startup parameter instead:
# URI form: "=" inside options is encoded as %3D
psql "postgresql://shop_owner:<password>@k7m2x9qa4pz1.us-east.db.keeldb.com:5432/shop?sslmode=require&options=endpoint%3Dk7m2x9qa4pz1"
# Keyword form, routed to the pooler
psql "host=k7m2x9qa4pz1.us-east.db.keeldb.com port=5432 dbname=shop user=shop_owner sslmode=require options=endpoint=k7m2x9qa4pz1-pooler"- The value is the database id, optionally with
-pooleror-ro. endpoint=<id>,--endpoint=<id>and-c endpoint=<id>are all accepted. Other options you pass, such as-c search_path=app, are kept.- KeelDB removes the endpoint option before the connection reaches PostgreSQL.
- When the client does send SNI, the hostname wins over
options.
Connection limits
| Plan | max_connections | Pooler client connections |
|---|---|---|
| Free | 100 | 1,000 |
| Launch | From your compute range: 200 per CU of the smaller of the maximum and 8 times the minimum, between 100 and 1,000 (400 with the default range of 0.25 to 2 CU, 800 with 0.5 to 4 CU) | 10,000 |
| Dedicated | By size: 100 (std-2), 200 (std-4), 400 (std-8, perf-8), 800 (perf-16), 1,000 (perf-32), 1,500 (perf-64), 2,000 (perf-128, perf-192) | 10,000 |
- Your role can use
max_connectionsminus 5; the other 5 are kept for KeelDB's own monitoring and maintenance. - The pooler opens at most 60% of
max_connections(at least 5) server connections to PostgreSQL per PgBouncer instance. HA databases, where offered, run one PgBouncer per copy. - A change of the compute range on Launch changes
max_connectionswith one restart; see Autoscaling.
Waking a sleeping database
Free databases, and Launch databases with scale to zero on, shrink to a small warm size after 5 idle minutes (or the idle time you set on Launch) and sleep fully after 60 more idle minutes. See Scale to zero. Dedicated databases are always on.
A client connected through the -pooler host counts as a connection for as long as it stays connected. The pooler's own idle connections to the database close one minute after your last pooled client disconnects, so they don't keep the database awake.
- From the warm size, the next connection grows the database back while the client connects.
- From a full sleep, the proxy wakes the database and holds the connection until it is ready, because PostgreSQL has to start again from its storage. Connections that arrive while it wakes wait the same way. If the database is not ready after 90 seconds, the connection fails with SQLSTATE
57P03and the messagedatabase is waking up from scale-to-zero, please retry. The wake continues, so a retry connects once it is ready. - Connections that don't sign in. The proxy wakes a sleeping database before the password is checked, so it limits wakes that never lead to a sign-in. A database woken that way goes back to sleep 10 minutes after it is up, unless a connection signs in to it: a sign-in gives it its normal idle time again. An address that woke the same database 3 times through the same KeelDB entry server without any connection from it signing in (a wrong password, or someone who only knows the host name) can't wake it for the next 24 hours. After that, each further wake from that address without a sign-in blocks it again, for twice as long each time, up to 7 days. A sign-in from the address clears its record, and so do 30 days without such a wake. While it is blocked, its connections to the sleeping database fail with SQLSTATE
57P03and the messagethis database is asleep, and connections from your address woke it repeatedly without signing in, and the hint says when it can wake it again. While the database is awake, connections from that address work as usual, and one that signs in lifts the block. So if an old client at your address caused the block (a job still using a former password, or another machine behind the same network address), wake the database from the console (run a query in the SQL editor) and connect your app while it's awake. An IP allowlist keeps other addresses from waking it at all. - When its server is full. A sleeping database wakes on the server that holds its storage. In the rare case that the server has no room left for it, we first put other Free databases that sit idle at their warm size to sleep, wake Launch databases before Free ones, and shrink busy Free databases to make room for a Launch one. Free databases together also stay within the room set aside for them. If there is still no room after about 40 seconds, the connection fails with SQLSTATE
53000and the messagedatabase could not wake up: its server is full right now. KeelDB is alerted; connect again in a minute.
Give clients a connect timeout that covers a wake, or retry: for a database that can sleep fully, raise connect_timeout in the connection string (for example to 30), since the default of 10 can end the first attempt before the database is up. Prisma 6 defaults to 5 seconds. The console SQL editor and the REST query endpoint don't wait: they start the wake and return a 409 conflict asking you to retry shortly.
Troubleshooting
| Error | SQLSTATE | Meaning |
|---|---|---|
KeelDB requires TLS: connect with sslmode=require | 28000 | The client tried a plaintext connection. |
no KeelDB database specified | 28000 | No SNI hostname and no options=endpoint=<id>. |
database endpoint "<id>" not found | 3D000 | The id in the hostname is wrong or the database was deleted. |
role "postgres" is reserved | 28000 | postgres, streaming_replica, cnpg_pooler_pgbouncer, keel_admin and root can't log in. Use your _owner role. |
IP address ... is not in the allowlist of this database | 28000 | See IP allowlist. |
too many failed authentication attempts from your IP address | 28000 | 20 failed logins in 10 minutes block your IP (for IPv6, its /64) for 15 minutes. |
too many failed authentication attempts from your network | 28000 | A large attack from your network (IPv4 /24, IPv6 /48) blocks its new clients for 15 minutes. See Brute-force protection. |
this database is suspended | 57P03 | Suspended. The hint says why: an unpaid invoice (see Failed payments), or a Free organization that used its CU-hours for the month (Free databases resume on the 1st, UTC). |
database is not available (provisioning) | 57P03 | Still being created or changed. Dedicated databases take longer to create than Free and Launch, because their servers are created first. Retry later. |
the database is restarting | 57P03 | A restart, a failover, a resize or a plan move switching over. Retry in a few seconds. |
cannot execute ... in a read-only transaction | 25006 | The database is read-only at a storage limit, or a Free database reached its daily write-ahead log cap. The console says which; see Storage. |
this database has no read replicas | 08004 | You used the -ro host on a database with neither a standby nor a read replica. |
the standby of this database is starting, the read replica of this database is starting | 57P03 | The -ro host of a database whose standby or first read replica does not serve yet: a new database or branch, or a replica you just added. Retry in a minute, or use the primary host meanwhile. With more than one replica, or a standby and replicas, the message says are starting. |
could not reach the database, please retry | 08006 | Transient routing failure. Retry with backoff. |
this database is asleep, and connections from your address woke it repeatedly without signing in | 57P03 | Your address woke this database 3 times without any connection from it signing in, so it can't wake it for 24 hours, and longer after each later wake without a sign-in. Check the user name and password. If yours are right, another client at your address caused it: wake the database from the console and connect while it's awake. See Waking a sleeping database. |
database could not wake up: its server is full right now | 53000 | A sleeping Free or Launch database found no room on its server within about 40 seconds. See Waking a sleeping database. Connect again in a minute. |
server login has been failing, cached error: ... | 08P01 | From the pooler: it could not reach PostgreSQL a moment ago, usually right after a restart or a failover. It tries again one second later. Retry the connection. Right after a wake the proxy retries for you. |
If you don't set application_name, the proxy sets it to keeldb-proxy. Set your own so you can tell sessions apart in Query insights.