Skip to content
betterstack-alchemyUnofficial

Managed databases

Better Stack Cloud runs databases for you: PostgreSQL (with PgBouncer and up to two read replicas), MySQL (a primary and up to two replicas), Valkey, a Redis-compatible store, ClickHouse on one node, and Kafka in KRaft mode with one or three brokers. Each is an instance you pick a plan (type) and engine version for, billed from creation by its plan and term, and reached over a private network or, with publicAccess: true, over TLS on a public host.

privatenetwork · 10.0.0.0/24
ApiService on Box
dbPostgres · PG1
host
private
pooled
PgBouncer
  • Apiconnects →db
An instance in networkIds is reachable on its host from servers in that network. A firewall in firewallIds filters what reaches it.

The smallest instance is a plan and a database name, here on a private network:

alchemy.run.ts
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],
});

The deploy blocks until the instance is running, which takes minutes; a failed or degraded instance fails it with WaitFailed, and one still provisioning after 30 minutes with WaitTimeout, picked up again by the next deploy. type rescales and engineVersion upgrades in place, each waited on until the instance runs again. database replaces it.

The Cloud lookups list plans and versions for every engine, at plan time:

alchemy.run.ts
const version = yield* BetterStack.Cloud.latestPostgresVersion().pipe(Effect.orDie);
const plans = yield* BetterStack.Cloud.postgresTypes().pipe(Effect.orDie);

The same pairs exist for MySQL, ClickHouse, Kafka and Valkey (mysqlTypes, latestKafkaVersion, …). See the Cloud lookups.

Use them to choose, then write the version into engineVersion as a literal. Passing latestPostgresVersion() straight into engineVersion would upgrade the instance on the first deploy after each new release, and a major upgrade can’t be undone.

PostgresDatabase adds a database to an instance and PostgresUser a SQL user with its access on each database:

alchemy.run.ts
yield* BetterStack.Cloud.PostgresDatabase("reports", {
postgresId: db.id,
name: "reports",
});
const reporter = yield* BetterStack.Cloud.PostgresUser("reporter", {
postgresId: db.id,
username: "reporter",
privileges: { reports: "read_write" },
});

A new database name replaces it, and drops the old database’s data. A user’s privileges change in place. The instance’s default admin user is managed by Better Stack.

Once an instance is running, its attributes carry everything a client needs: host, the ports, the default user, its password, the database, ready-made connection URIs with the password in them, and Better Stack’s caCertificate for TLS verification. Passwords and URIs are Redacted: they never show up in plans or logs. A PostgresUser carries the same URIs with its own password, so an application can connect as a least-privilege user rather than admin:

alchemy.run.ts
const env = {
// postgresql:// with the password and sslmode=verify-full, through PgBouncer
DATABASE_URL: reporter.pooledConnectionUri,
// Better Stack's CA (PEM), for verify-full
PG_CA_CERT: db.caCertificate,
};

Give the env to a Service and read it with Config.Redacted("DATABASE_URL"). For a client configured field by field, use the parts:

alchemy.run.ts
const parts = {
PGHOST: db.host,
PGPORT: db.pooledPort,
PGDATABASE: db.database,
PGUSER: db.user, // the instance's admin user
PGPASSWORD: db.password, // Redacted
};
Engine Password URIs Notes
Postgres password (admin) connectionUri, pooledConnectionUri (PgBouncer), publicConnectionUri, publicPooledConnectionUri sslmode=verify-full with caCertificate
MySQL password (admin) connectionUri, publicConnectionUri TLS required (ssl-mode=REQUIRED)
Valkey authToken (user default) connectionUri (valkey://, private, no TLS), tlsConnectionUri (valkeys://, public) caCertificate for the public TLS endpoint
ClickHouse password (admin) connectionUri, publicConnectionUri (native protocol over TLS) httpsUrl has no credentials: send user/password as basic auth
Kafka password (user default) bootstrapServers properties: ready-made librdkafka client settings; a KafkaUser carries its own

The public… URIs are undefined while publicAccess is off.

A deploy never rotates credentials on its own. Change rotateCredentials to a new value to rotate the instance’s password (Valkey: its AUTH token) once:

alchemy.run.ts
const db = yield* BetterStack.Cloud.Postgres("db", {
type: "PG1",
database: "app",
// Change the value to rotate the admin password once; the next deploy
// reads the new password and URIs into the attributes.
rotateCredentials: "2026-12",
});

The deploy reads the new password and URIs into the attributes, so everything that takes them from the instance picks them up on the same deploy. Open connections keep working; new ones need the new password. On MySQL and ClickHouse the previous password keeps working for a while, until rotatingUntil. A rotation done in Better Stack’s console or CLI is read on the next deploy, without a replace.

Postgres and MySQL take migrations: a directory of SQL migrations applied on every deploy, after the instance is running, through Alchemy’s shared migration engine (@alchemy.run/sql). Install @alchemy.run/sql and pg (Postgres) or mysql2 (MySQL) next to this package; they are optional peer dependencies, loaded only when a resource has migrations.

The deploying machine connects to the instance’s public endpoint as admin, with TLS verified against caCertificate. Nothing is opened for you: the instance needs publicAccess: true and a firewall rule that admits the deploying machine on the database port (5432 for Postgres, 3306 for MySQL). Without them the deploy fails with MigrationsUnreachable, which says what to set:

alchemy.run.ts
// Only the deploying machine may reach the public endpoint.
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"],
});
const db = yield* BetterStack.Cloud.Postgres("db", {
type: "PG1",
database: "app",
publicAccess: true,
firewallIds: [firewall.id],
networkIds: [network.id],
migrations: "./migrations",
});
  • Each file runs once, in name order, its statements and its row in the __alchemy_migrations table in one transaction. migrationsHashes records what was applied, 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. On MySQL, DDL commits implicitly, so a failing file can leave its earlier statements applied.
  • migrations also takes { dir, table } to name the bookkeeping table, or a Drizzle.Schema. Directories written by drizzle-kit or Prisma work as they are.

To keep the instance private, leave migrations out and apply them where the database is reachable: at startup of a Service on the instance’s network, with @alchemy.run/sql’s executors and runMigrations over connectionUri, or from CI with network access. The migrations prop is tested offline only (a recording fake and an in-process Postgres), not against a live instance; see Compatibility and the Postgres and MySQL references.

A scheduled snapshot runs hourly, daily, weekly or monthly:

alchemy.run.ts
yield* BetterStack.Cloud.PostgresScheduledSnapshot("daily", {
postgresId: db.id,
frequency: "daily",
});

MySQLScheduledSnapshot, ValkeyScheduledSnapshot and ClickHouseScheduledSnapshot take their instance’s id the same way. See Better Stack’s database snapshots docs.

A PostgresSnapshot is one snapshot, taken when it is created (Better Stack flushes the primary’s data first) and deleted with the stack; MySQLSnapshot, ValkeySnapshot and ClickHouseSnapshot work the same way:

alchemy.run.ts
yield* BetterStack.Cloud.PostgresSnapshot("before-migration", { postgresId: db.id });

It has no update: a new name or metadata takes a new snapshot and deletes the old one. Restoring creates a new instance or rolls the instance back, an action rather than desired state; see the PostgresSnapshot reference.

A primary with up to two asynchronous replicas:

alchemy.run.ts
const orders = yield* BetterStack.Cloud.MySQL("orders", {
type: "MY1",
networkIds: [network.id],
});

host, port, publicHost, password and the connection URIs are attributes. See the MySQL reference.

A Redis-compatible store with one primary and up to two replicas. Plain connections go to host:port from the private network; publicAccess adds TLS on publicHost:tlsPort.

alchemy.run.ts
const cache = yield* BetterStack.Cloud.Valkey("cache", {
type: "VK1",
persistence: "none",
evictionPolicy: "allkeys-lru",
networkIds: [network.id],
});

See the Valkey reference.

One node with no replicas, so snapshots are how you recover from data loss. The user is admin and the database defaultdb.

alchemy.run.ts
const analytics = yield* BetterStack.Cloud.ClickHouse("analytics", {
type: "CH1",
networkIds: [network.id],
});

host, publicHost, httpsUrl, publicHttpsUrl, password and the connection URIs are attributes. See the ClickHouse reference.

A cluster of one broker (development) or three (survives losing one). Every connection uses TLS and SASL with SCRAM-SHA-512. Clients can’t create topics, so declare them, and the users that may use them:

alchemy.run.ts
const events = yield* BetterStack.Cloud.Kafka("events", {
type: "KA1",
brokerCount: 3,
networkIds: [network.id],
});
yield* BetterStack.Cloud.KafkaTopic("orders-topic", {
kafkaId: events.id,
name: "orders",
partitions: 6,
});
yield* BetterStack.Cloud.KafkaUser("producer", {
kafkaId: events.id,
username: "orders-producer",
privileges: [{ topicPattern: "orders", permission: "produce" }],
});

brokerCount replaces the cluster, and its data: Kafka clusters have no snapshots. A topic’s partitions can only grow. A user’s privileges are topic names or prefixes ending in *, each with consume, produce or produce_consume. Clients connect with the cluster’s bootstrapServers, securityProtocol, saslMechanism, a user’s username and password and the caCertificate, or take all of them at once from properties. See the Kafka reference.

Every Postgres, MySQL, Valkey, ClickHouse and Kafka instance this stack creates carries an alchemy entry in its metadata, which takes one of its 10 metadata slots. A deploy that lost track of an instance finds it by that marker instead of creating (and billing) another, and alchemy nuke lists only Alchemy-created instances. See the Postgres reference; the others say the same.

teamId and availabilityZone replace any instance, which deletes its data. A replacement that keeps an explicit name deletes the old instance first, because names are unique among live instances. After a delete, the API keeps answering with status: "destroyed" for a while, which reads as gone.