Skip to content
betterstack-alchemyUnofficial

Cloud.MySQL

Kind ResourceType id BetterStack.Cloud.MySQLSource src/Cloud/MySQL.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/MySQL.test.ts).

A managed MySQL instance on Better Stack Cloud, with a primary and up to two read replicas that copy it asynchronously. 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 MySQLScheduledSnapshot 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 listFlatMysqlSnapshot / deleteFlatMysqlSnapshot. A MySQLSnapshot of this stack is deleted with the stack.

What changes in place: name, term, metadata, publicAccess, replicaCount and the MySQL settings (defaultTimeZone, maxAllowedPacket, sqlMode, sqlRequirePrimaryKey); type (a rescale) and engineVersion (an upgrade, one way), each waited on until running again; networkIds and firewallIds (attach/detach). What replaces it: teamId and 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 and publicHost come from the instance’s endpoint; user, password, database, connectionUri, publicConnectionUri 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 (the previous one keeps working for 24 hours, rotatingUntil); 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 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.MySQL("db", {
type: "MY1",
networkIds: [network.id],
});

Tuned, with a replica

yield* BetterStack.Cloud.MySQL("orders", {
type: "MY2",
replicaCount: 1,
defaultTimeZone: "UTC",
sqlRequirePrimaryKey: true,
});

connectionUri reaches the primary from the instance’s private networks; publicConnectionUri over the internet, only with publicAccess: true. Both require TLS and carry the password (Redacted).

A Cloud.Service reading the URI from its environment

const db = yield* BetterStack.Cloud.MySQL("db", { type: "MY1" });
// In the Service's props: env: { DATABASE_URL: db.connectionUri }
// In its program: const url = yield* Config.Redacted("DATABASE_URL");

The parts, for a client configured field by field

const env = {
MYSQL_HOST: db.host,
MYSQL_PORT: db.port,
MYSQL_USER: db.user,
MYSQL_PASSWORD: db.password,
MYSQL_DATABASE: db.database,
};

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 mysql2 — 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 3306; 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 (MySQL commits DDL implicitly, so a failing file can leave its earlier statements applied); 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 file is not recorded (its bookkeeping row rolls back) and the earlier files stay applied; but DDL it had already run stays too, because MySQL commits DDL implicitly. Keep one DDL statement per file (or make it idempotent), 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: 3306,
ipAddresses: ["203.0.113.7/32"], // the deploying machine
});
const db = yield* BetterStack.Cloud.MySQL("db", {
type: "MY1",
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.MySQL.lookup({ id: "42" });

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

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

type string required

The instance's type, which sets its size, such as MY1. List the types with the SDK's listMysqlType (or betterstack mysql-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.

defaultTimeZone string

The default time zone. Accepts SYSTEM, UTC, an offset from -13:59 to +14:00, or an IANA time zone name such as Europe/Prague.

engineVersion string

The MySQL version, as major and minor, such as 8.4. Defaults to the latest version. List them with the SDK's listMysqlVersion (or betterstack mysql-version list); availableEngineVersions on the attributes says which ones this instance can move to. Changes in place: an 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.

maxAllowedPacket number

The largest packet MySQL accepts, in bytes, from 16777216 to 1073741824.

metadata CreateMysqlRequestMetadataMap

Your tags, as an object of string keys and values. An update replaces every tag.

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 MySQL 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 instance is also reachable on public IP addresses. Clients must connect with TLS.

replicaCount number

The number of read replicas, 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.

sqlMode string

The SQL modes, separated by commas, such as STRICT_TRANS_TABLES,NO_ZERO_DATE. Removing the prop resets MySQL's default modes.

sqlRequirePrimaryKey boolean

Whether new tables must have a primary key.

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.

availabilityZone string always set

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

caCertificate string always set

The CA certificate (PEM) that signs the instance's TLS certificate.

connectionUri Redacted<string> always set

mysql:// URI for clients on your private networks, with the password and ssl-mode=REQUIRED (credentials uri).

database string always set

The default database's name (credentials database).

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

port number always set

The port to connect to, 3306 (endpoint.port).

publicConnectionUri Redacted<string> always set

The same for clients on 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. Clients must use TLS.

rotatingUntil string always set

After a rotation: when the previous password stops working (24 hours later); undefined otherwise.

user string always set

The admin user, admin (credentials user).

availableEngineVersions string[]

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

createdAt string

When the instance was created.

defaultTimeZone string

The default time zone. Accepts SYSTEM, UTC, an offset from -13:59 to +14:00, or an IANA time zone name such as Europe/Prague.

endpoint MysqlEndpoint

Where clients connect to the current primary.

enginePatchVersion string | null

The exact MySQL release installed, or null until it's known.

engineVersion string

The MySQL version, as major and minor, such as 9.7. List the versions with betterstack mysql-version list. Defaults to the latest version.

firewallIds string[]

The ID of the firewall attached to every member. An instance can have one firewall.

latestSnapshotAt string | null

When the newest available snapshot was taken, or null when there's none.

maxAllowedPacket number

The largest packet MySQL accepts, in bytes, from 16777216 to 1073741824.

maxConnections number

The most connections the instance accepts at once.

members MysqlMembersItem[]

The instance's members, the primary and its replicas. A replica's replication_lag_seconds says how far behind the primary it is, and it's null on the primary.

metadata MysqlMetadataMap

Your tags, as an object of string keys and values. An update replaces every tag.

name string

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

networkIds string[]

The IDs of your networks attached to every member. Each network must be in the instance's team.

preUpgradeSnapshotId string

The ID of the snapshot we created before the upgrade.

publicAccess boolean

Whether the instance is also reachable on public IP addresses. Clients must connect with TLS.

readOnly boolean

Whether the instance accepts only reads because its disk is almost full.

replicaCount number

The number of read replicas, from 0 to 2.

sqlMode string | null

The SQL modes, separated by commas, such as STRICT_TRANS_TABLES,NO_ZERO_DATE. Is null for MySQL's default modes.

sqlRequirePrimaryKey boolean

Whether new tables must have a primary key.

status string

The instance's state. - provisioning: We're starting the members and installing MySQL. - running: The instance is ready. - degraded: A member is down, replication is broken or the disk is almost full. status_message says which. - rescaling: We're changing the instance's type. - upgrading: We're upgrading the instance to a newer MySQL version. - restoring: We're restoring the instance from a snapshot. - failed: We couldn't create the instance. status_message says why. Create a new one instead. - destroyed: The instance is destroyed.

statusMessage string | null

Why the instance is in its current state, such as what failed or which operation didn't finish. Is null when there's nothing to report.

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: Billed every month. - annual: Paid for a year.

type string

The instance's type, such as MY1. List the types with betterstack mysql-type list.

updatedAt string

When the instance was last updated.

usableDiskGb number

The disk space for your data, in GiB.

MySQL.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.