Skip to content
betterstack-alchemyUnofficial

Cloud.Postgres

Kind ResourceType id BetterStack.Cloud.PostgresSource src/Cloud/Postgres.tsLive test gated Lifecycle test runs against the offline mock; a live run exists but is gated behind BETTERSTACK_TEST_CLOUD_BILLABLE=1 because it bills; live runs need the owner's go-ahead (test/Cloud/Postgres.test.ts).

A managed PostgreSQL instance on Better Stack Cloud, with PgBouncer for connection pooling and up to two read replicas. It bills from creation (monthly by default; term: "annual" commits a year).

The deploy blocks until the instance is running (minutes); a failed or degraded instance fails it with WaitFailed, and one still provisioning after 30 minutes with WaitTimeout (the work carries on, and the next deploy picks it up). An instance that ends destroyed reads as gone, so the wait runs into WaitTimeout too.

What outlives a destroy, and keeps billing. Snapshots outlive their database: removing the instance keeps every snapshot, the ones its PostgresScheduledSnapshot took included, and they stay billed (“Database snapshots are billed like server snapshots”). This stack doesn’t track the scheduled ones (they carry no marker), so alchemy destroy and nuke leave them: remove them in Databases → Snapshots, or with the SDK’s listFlatPostgresSnapshot / deleteFlatPostgresSnapshot. A PostgresSnapshot of this stack is deleted with the stack.

What changes in place: name, term, metadata, publicAccess, replicaCount and the PostgreSQL settings (statementTimeout, idleInTransactionSessionTimeout, logMinDurationStatement, workMemMb); type (a rescale) and engineVersion (a major upgrade, one way), each waited on until running again; networkIds and firewallIds (attach/detach). What replaces it: database, teamId, availabilityZone. A replacement that keeps an explicit name deletes the old instance first (names are unique among live instances).

Networking: the instance is reachable on host from the Networks in networkIds; with publicAccess: true also on publicHost over TLS. A Firewall in firewallIds filters what reaches it.

Connection details: host, port, pooledPort and publicHost come from the instance’s endpoint; user, password, database, the connection URIs and caCertificate from the credentials endpoint, read once the instance is running. Secrets are Redacted.

Credentials: the deploy never rotates them on its own. Set rotateCredentials to a new value to rotate the admin password once (open connections keep working, new ones need the new password); a rotation done in the console or CLI is read on the next deploy, without a replace.

After delete the API keeps answering the instance with status: "destroyed" for a while; that reads as gone. Its databases, users and snapshot schedules go with it.

The smallest instance, on a private network

const network = yield* BetterStack.Cloud.Network("private", {
ipPrefix: "10.0.0.0",
ipPrefixLength: 24,
});
const db = yield* BetterStack.Cloud.Postgres("db", {
type: "PG1",
database: "app",
networkIds: [network.id],
});

Tuned, with a replica and public TLS access

yield* BetterStack.Cloud.Postgres("analytics", {
type: "PG2",
engineVersion: "17",
replicaCount: 1,
publicAccess: true,
statementTimeout: 30_000,
metadata: { team: "data" },
});

Which URI: connectionUri connects directly (port 5432) from the instance’s private networks — use it for migrations, long-lived pools and session features (LISTEN, prepared statements across transactions). pooledConnectionUri goes through PgBouncer (port 6432) — use it for many short connections. The public* variants are the same over the internet, only with publicAccess: true (TLS, sslmode=verify-full against caCertificate). All URIs carry the password and are Redacted.

A Cloud.Service reading the URI from its environment

const db = yield* BetterStack.Cloud.Postgres("db", { type: "PG1", networkIds: [network.id] });
// In the Service's props: env: { DATABASE_URL: db.pooledConnectionUri }
// In its program: const url = yield* Config.Redacted("DATABASE_URL");

The parts, for a client configured field by field

const env = {
PGHOST: db.host,
PGPORT: db.port,
PGDATABASE: db.database,
PGUSER: db.user,
PGPASSWORD: db.password,
PGSSLMODE: "verify-full",
};

Rotate once by changing the value

yield* BetterStack.Cloud.Postgres("db", { type: "PG1", rotateCredentials: "2026-12" });

Change the type and the major version in place

yield* BetterStack.Cloud.Postgres("db", { type: "PG2", engineVersion: "18", database: "app" });

migrations applies SQL migrations on every deploy, after the instance is running and its credentials are read, through Alchemy’s shared engine (@alchemy.run/sql/Migrations; install it and pg — optional peer dependencies). The deploying machine connects over the PUBLIC endpoint (publicConnectionUri) as the admin user, TLS verified against caCertificate, so the instance needs publicAccess: true and a Firewall rule admitting that machine on TCP 5432; nothing is opened for you. Without them the deploy fails with the typed MigrationsUnreachable (reason: "no-public-endpoint" or "connection-failed") saying what to set. A deploy connects only when a file is pending (compared with migrationsHashes), so once the directory is applied you can turn publicAccess off (or drop the firewall rule) and keep deploying other changes; turn it on again for the next migration.

Each file runs once, in name order, its statements and its row in the __alchemy_migrations table in one transaction; migrationsHashes records them, so an unchanged directory is a no-op and a new file is an in-place update (never a replace). History is forward-only: editing or deleting an applied file fails the deploy with RewrittenMigrationHistoryError, and a new file that sorts before an applied one with NonLinearMigrationHistoryError — add a new migration instead. A failed migration rolls back and leaves the earlier ones applied; fix it and deploy again. Directories written by drizzle-kit or Prisma work as they are, and migrations also takes a Drizzle.Schema.

Migrations from this machine, the app on the private network

const firewall = yield* BetterStack.Cloud.Firewall("db-access", {});
yield* BetterStack.Cloud.FirewallRule("deployer", {
firewallId: firewall.id,
direction: "inbound",
protocol: "tcp",
portFrom: 5432,
ipAddresses: ["203.0.113.7/32"], // the deploying machine
});
const db = yield* BetterStack.Cloud.Postgres("db", {
type: "PG1",
publicAccess: true,
firewallIds: [firewall.id],
networkIds: [network.id],
migrations: "./migrations",
});
// A Cloud.Service on the same network: env: { DATABASE_URL: db.connectionUri }

Without public access, run the migrations where the database is reachable instead: leave migrations out and apply them at startup of a Cloud.Service on the instance’s network (with @alchemy.run/sql’s withPgExecutor/withMySqlExecutor and runMigrations over connectionUri), or from CI with network access.

Reference an instance by id

const existing = BetterStack.Cloud.Postgres.lookup({ id: "42" });

Reference an instance by name (fails with AmbiguousLookup when several share it)

const byName = BetterStack.Cloud.Postgres.lookup({ name: "app-db" });

type string required

The PostgreSQL type, which sets the instance's size (CPU, memory, storage), such as PG1. List the types with the SDK's listPostgresType (or betterstack postgres-type list). Changes in place: a rescale, waited on until the instance is running again on the new type.

availabilityZone string

Availability zone the resource lives in, such as us-west-2a. Defaults to the credentials' zone (BETTERSTACK_AVAILABILITY_ZONE, or the profile's). Changing it replaces the resource. A child of a resource in another zone (a firewall rule, a node pool, a snapshot of an instance outside the credentials' zone) must repeat the parent's availabilityZone: it receives only the parent's id, so its zone cannot be derived.

database string

The name of the first database, created with the instance. Defaults to defaultdb. The API never returns it (it is kept from the config), and it can't change: changing it replaces the whole instance, data included. Add more databases with [PostgresDatabase](/reference/cloud/postgresdatabase/).

engineVersion string

The PostgreSQL major version, such as 17. Defaults to the newest version offered. List them with the SDK's listPostgresVersion (or betterstack postgres-version list); availableEngineVersions on the attributes says which ones this instance can move to. Changes in place: a major-version upgrade, waited on until the instance is running on the new version. An upgrade can't be undone: a lower version is refused by the API.

firewallIds string[]

The ID of the [Firewall](/reference/cloud/firewall/) attached to every member, at most one. Changes in place (the old one is detached before the new one is attached). Removing the prop keeps what is attached; [] detaches it.

idleInTransactionSessionTimeout number

How long a session can stay idle inside a transaction before PostgreSQL ends it, in milliseconds, from 0 to 86400000. Set it to 0 for no limit.

logMinDurationStatement number

How long a statement must run before we log it, in milliseconds, from -1 to 600000. Set it to -1 to log none.

metadata CreatePostgresRequestMetadataMap

Your own tags, as string keys and values. An update replaces all tags.

migrations string | { dir: string; table?: string | undefined; } | { out: string; }

SQL migrations to apply on deploy, after the instance is running: a directory (flat .sql files sorted by name, or a drizzle-kit / Prisma layout), { dir, table }, or a Drizzle.Schema. Applied over the instance's PUBLIC endpoint from the deploying machine (needs publicAccess: true and a firewall rule for that machine). History is forward-only: a new file must sort after every applied one (NonLinearMigrationHistoryError otherwise), and an applied file that was edited or removed fails the deploy with RewrittenMigrationHistoryError; add a new migration instead. Renaming an applied file without changing it keeps it applied. Bookkeeping is the __alchemy_migrations table. Needs the optional peer dependencies @alchemy.run/sql and the driver (pg or mysql2).

name string

The instance's name, at most 255 characters, unique among the team's PostgreSQL instances that aren't destroyed or failed. Defaults to a unique name generated from the stack, stage and logical id. Changes in place.

networkIds string[]

The IDs of your [Network](/reference/cloud/network/)s attached to every member; they must belong to the instance's team. Changes in place (attach and detach actions). Removing the prop keeps what is attached; [] detaches all.

publicAccess boolean

Whether the direct and pooled endpoints are also reachable from the internet. Connections use TLS.

replicaCount number

How many read replicas the instance has, from 0 to 2.

rotateCredentials string

Rotate the credentials: every change of this value after create (for example a date, "2026-12") calls the API's rotate operation once on the next deploy, and the new secrets replace the old ones in the attributes (and so in every env that references them). Leaving it out, or keeping the same value, never rotates. A rotation done in the console or CLI is simply read on the next deploy.

statementTimeout number

How long a statement can run before PostgreSQL cancels it, in milliseconds, from 0 to 3600000. Set it to 0 for no limit.

teamId string

Team that owns the resource, such as t123. Defaults to the credentials' team (BETTERSTACK_TEAM_ID, or the profile's team). Changing it replaces the resource.

term "monthly" | "annual"

The billing term: monthly (the default) or annual. annual commits you to paying for a whole year. A change applies at once and starts a new term.

workMemMb number

The memory each sort or hash operation can use, in MiB, from 1 to 256.

availabilityZone string always set

Availability zone the resource lives in, such as us-west-2a.

caCertificate string always set

Better Stack's CA certificate (PEM) that signed the server's certificate, for verify-full.

connectionUri Redacted<string> always set

postgresql:// URI for direct connections from your private networks, with the password and sslmode=verify-full (credentials uri).

database string always set

The database the URIs connect to (credentials database): defaultdb when the instance has it, else its first database by name.

host string always set

The hostname to connect to from your private networks (endpoint.hostname). It follows the current primary.

id string always set

The instance's ID.

migrationsDir string always set

Directory of the applied SQL migrations (undefined without migrations).

migrationsHashes Record<string, string> always set

Content hash (sha256) of every applied migration file, by name.

migrationsTable string always set

The bookkeeping table the migrations were recorded in.

password Redacted<string> always set

The admin user's password (credentials password).

pooledConnectionUri Redacted<string> always set

The same through PgBouncer (pooledPort, transaction pooling) from your private networks (credentials pooled_uri). Prefer it for many short connections (serverless, per-request clients).

pooledPort number always set

The port for connections through PgBouncer, 6432 (endpoint.pooledPort).

port number always set

The port for direct connections, 5432 (endpoint.port).

publicConnectionUri Redacted<string> always set

Direct connections from the internet, undefined while publicAccess is off (credentials public_uri).

publicHost string always set

The hostname to connect to from the internet (endpoint.publicHostname), undefined while publicAccess is off. Connections use TLS.

publicPooledConnectionUri Redacted<string> always set

Through PgBouncer from the internet, undefined while publicAccess is off (credentials public_pooled_uri).

user string always set

The instance's admin user (credentials user).

availableEngineVersions string[]

The major versions you can upgrade the instance to. An upgrade can't be undone.

createdAt string

When the instance was created.

databases string[]

The names of the instance's databases, sorted. Add and remove them with betterstack postgres-database.

endpoint PostgresEndpoint

Where to connect to the instance. Connect directly on port, or through PgBouncer on pooled_port.

enginePatchVersion string | null

The exact PostgreSQL version the instance runs, such as 19.0, or null until we know it.

engineVersion string

The PostgreSQL major version, such as 19. List the versions with betterstack postgres-version list. Defaults to the newest version we offer.

firewallIds string[]

The ID of the firewall attached to every member, at most one.

idleInTransactionSessionTimeout number

How long a session can stay idle inside a transaction before PostgreSQL ends it, in milliseconds, from 0 to 86400000. Set it to 0 for no limit.

latestSnapshotAt string | null

When the newest available snapshot was taken.

logMinDurationStatement number

How long a statement must run before we log it, in milliseconds, from -1 to 600000. Set it to -1 to log none.

maxConnections number

The most direct connections to PostgreSQL at once.

maxPooledConnections number

The most client connections to PgBouncer at once.

members PostgresMembersItem[]

The primary and the replicas that run the instance.

metadata PostgresMetadataMap

Your own tags, as string keys and values. An update replaces all tags.

name string

The instance's name, at most 255 characters. Must be unique among the organization's PostgreSQL instances that aren't destroyed or failed.

networkIds string[]

The IDs of your networks attached to every member. Must belong to the instance's team.

preUpgradeSnapshotId string

The ID of the snapshot we created before the upgrade.

publicAccess boolean

Whether the direct and pooled endpoints are also reachable from the internet. Connections use TLS.

readOnly boolean

Whether we've made PostgreSQL read-only because its disk is nearly full.

replicaCount number

How many read replicas the instance has, from 0 to 2.

statementTimeout number

How long a statement can run before PostgreSQL cancels it, in milliseconds, from 0 to 3600000. Set it to 0 for no limit.

status string

The instance's status. After you create or restore an instance, get it until its status is running. A failed or destroyed instance stays that way. - provisioning: We're setting up the instance. - running: The instance is ready. - degraded: A member is down, replication is broken or the disk is nearly full. status_message says which. - rescaling: We're changing the instance's type. - upgrading: We're upgrading PostgreSQL to a new major version. - restoring: We're restoring the instance from a snapshot. - failed: Setting up the instance failed. status_message says why. - destroyed: The instance is destroyed.

statusMessage string | null

More about the status, such as why the instance failed or is degraded, a replica being rebuilt or an action that didn't finish.

teamId string

The ID of the team that owns the instance. betterstack team list shows it. Can't be changed after the instance is created.

term "monthly" | "annual"

The billing term. Defaults to monthly. A change applies at once, from monthly to annual or back. Billing ends the current term and starts the new one. Sending the current term changes nothing. - monthly: The instance is billed each month. - annual: The instance is paid for a year at a time.

type string

The PostgreSQL type, which sets the instance's size. List the types with betterstack postgres-type list.

updatedAt string

When the instance was last updated.

usableStorageGb number

The disk space for your data, in GiB.

users PostgresUsersItem[]

The instance's SQL users. Add and remove users and get their passwords with betterstack postgres-user.

workMemMb number

The memory each sort or hash operation can use, in MiB, from 1 to 256.

Postgres.lookup(props) reads an object this stack does not manage. It is never created, updated or deleted.

availabilityZone string

Zone it lives in, such as us-west-2a. Defaults to the credentials' zone.