Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

feat(infra): configure Cloud Run sizing and API database pool limits per stage (#3063)

zombee0e3900de8ebb5
diff --git a/apps/api/README.md b/apps/api/README.md
index 301ae0190..6262df220 100644
--- a/apps/api/README.md
+++ b/apps/api/README.md
@@ -1616,7 +1616,8 @@ for reference syntax and deployment behavior.
Run Node 24 and use `make build:apps:api`. On GCP Cloud Run, background scheduling
requires CPU allocation while idle and at least one minimum instance. mdeploy adds
-`cpuIdle: false` for custom domains and a service-level minimum of one instance when hosted CI is configured.
+`cpuIdle: false` for custom domains and defaults to one minimum instance when hosted CI is configured.
+An explicit `deploy.api.minInstances` overrides that default, including zero.
This incurs idle instance costs. The database lease handles restarts and overlapping replicas; minimum instances
do not guarantee that a process never restarts. These settings and formal hosted-App CI
still require dev deployment acceptance.
diff --git a/apps/infra/docs/configuration.md b/apps/infra/docs/configuration.md
index 883454d43..ee5090495 100644
--- a/apps/infra/docs/configuration.md
+++ b/apps/infra/docs/configuration.md
@@ -152,6 +152,11 @@ An array group makes every key required. An object distinguishes `required` from
Missing required values fail before deployment. Optional values enable features only when supplied.
The exact key list lives in the manifest; avoid maintaining a second list in a runbook.
+## API database connection pool
+
+Set `DB_POOL_MAX` in the stage store to limit the number of PostgreSQL connections per API instance.
+Redeploy the API to deliver the value, for example `25`, through the optional API environment group.
+
## Invitation link lifetime
Set `ORGANIZATION_INVITATION_TTL_SECONDS` in the stage store to change the default
diff --git a/apps/infra/docs/gcp/deployment.md b/apps/infra/docs/gcp/deployment.md
index 56eed49b8..a63b80724 100644
--- a/apps/infra/docs/gcp/deployment.md
+++ b/apps/infra/docs/gcp/deployment.md
@@ -104,7 +104,17 @@ The API also requires its existing Commerce connection for subscription eligibil
Customer CNAME records must use DNS-only mode; see the [DNS guide](../../../../docs/concepts/networking.md#bring-your-own-domain).
Custom domains set Cloud Run `cpuIdle: false`, incurring CPU costs while an instance exists, without adding a minimum instance count.
-Hosted CI independently sets a service-level minimum of one when enabled.
+In the mstage declaration, `"instance": { "cpu": 2, "memoryMiB": 2048 }` under `deploy.api`
+requests 2 vCPU and 2 GiB for each API container. Set both fields together, or omit `instance`
+to leave container limits unspecified. CPU and memory must fit the
+[Cloud Run service limits](https://cloud.google.com/run/docs/configuring/services/memory-limits).
+
+Set `deploy.api.minInstances` in the mstage declaration to override the service-level minimum (for example, `5`).
+An explicit `0` allows scale-to-zero even with hosted CI. When omitted, hosted CI sets a minimum of one; otherwise the minimum is omitted.
+
+Set `deploy.api.maxInstances` to a positive integer (for example, `15`) to cap both the service and its new revision.
+The maximum must be at least the configured minimum. Omitting it leaves the maximum unspecified.
+
The API task runs at startup and every minute, advancing at most three due confirmed setups and one maintenance round.
Startup awaits that work; hostname leases coordinate replicas, and shutdown awaits the active round.
Scale-to-zero pauses progress until the API starts again; no independent Cloud Scheduler or expiration alerts are provisioned.
diff --git a/apps/infra/mdeploy/README.md b/apps/infra/mdeploy/README.md
index b12bc612b..df13825fc 100644
--- a/apps/infra/mdeploy/README.md
+++ b/apps/infra/mdeploy/README.md
@@ -94,7 +94,8 @@ webhook active until a coordinated hosted cutover can avoid duplicate providers.
Pin secret versions and deploy a new revision when rotating them. The API receives
the resolved values at instance startup; it does not fetch Secret Manager itself.
The GCP API retains `cpuIdle: false` for custom-domain background work.
-Hosted CI additionally configures a service-level minimum of one instance; custom domains add no minimum.
+Set `deploy.api.minInstances` in the mstage declaration to configure the Cloud Run service minimum, including zero.
+When omitted, hosted CI sets a minimum of one; otherwise the service minimum is omitted.
Continuous CPU applies only while an instance exists and incurs idle instance costs.
Multiple replicas use the PostgreSQL lease to select one CI scheduler.
diff --git a/apps/infra/mdeploy/src/config.ts b/apps/infra/mdeploy/src/config.ts
index 7a9245d5f..e25ece079 100644
--- a/apps/infra/mdeploy/src/config.ts
+++ b/apps/infra/mdeploy/src/config.ts
@@ -29,6 +29,7 @@
import { dirname } from 'node:path'
import { loadConfig as loadMstageConfig, stageIn } from 'mstage/config'
+import type { ApiRequest } from '../stack/api.ts'
import type { AlarmRequest, AlarmThreshold } from '../stack/alarms.ts'
import type { CacheRequest, CacheSize } from '../stack/cache.ts'
import type { ClickHouseMode, ClickHouseRequest } from '../stack/clickhouse.ts'
@@ -51,6 +52,7 @@ export type DeployConfig = {
path: string
/** The directory holding the committed base file, which is mstage's answer. */
root: string
+ api?: Pick<ApiRequest, 'minInstances' | 'maxInstances' | 'instance'>
database: DatabaseRequest
cache: CacheRequest
storage: StorageRequest
@@ -283,6 +285,42 @@ const parseAlarms = (raw: unknown, where: string, { partial }: { partial: boolea
return parsed
}
+// Cloud Run service limits with instance-based billing (cpuIdle: false).
+const API_MEMORY_MIB = new Map([
+ [1, { min: 512, max: 4096 }],
+ [2, { min: 512, max: 8192 }],
+ [4, { min: 2048, max: 16384 }],
+ [6, { min: 4096, max: 24576 }],
+ [8, { min: 4096, max: 32768 }],
+])
+
+const parseApi = (raw: unknown, where: string): NonNullable<DeployConfig['api']> => {
+ const block = assertObject(raw, where)
+ assertKeys(block, ['minInstances', 'maxInstances', 'instance'], where, { partial: true })
+ const parsed: NonNullable<DeployConfig['api']> = {}
+ if ('minInstances' in block) {
+ parsed.minInstances = assertWholeNumber(block.minInstances, `${where}.minInstances`, { min: 0, max: 2_147_483_647 })
+ }
+ if ('maxInstances' in block) {
+ parsed.maxInstances = assertWholeNumber(block.maxInstances, `${where}.maxInstances`, { min: 1, max: 2_147_483_647 })
+ if (parsed.minInstances !== undefined && parsed.maxInstances < parsed.minInstances) {
+ throw new DeployConfigError(`${where}.maxInstances must be at least minInstances`)
+ }
+ }
+ if ('instance' in block) {
+ const path = `${where}.instance`
+ const instance = assertObject(block.instance, path)
+ assertKeys(instance, ['cpu', 'memoryMiB'], path, { partial: false })
+ const cpu = instance.cpu
+ const bounds = typeof cpu === 'number' && API_MEMORY_MIB.get(cpu)
+ if (typeof cpu !== 'number' || !bounds) {
+ throw new DeployConfigError(`${path}.cpu must be one of ${[...API_MEMORY_MIB.keys()].join(', ')}`)
+ }
+ parsed.instance = { cpu, memoryMiB: assertWholeNumber(instance.memoryMiB, `${path}.memoryMiB`, bounds) }
+ }
+ return parsed
+}
+
const PARSERS = {
database: parseDatabase,
cache: parseCache,
@@ -300,12 +338,14 @@ export const parseDeployConfig = (path: string, contents: string): DeployConfig
throw new DeployConfigError(`${path} is not valid JSON: ${(error as Error).message}`)
}
const root = assertObject(raw, path)
- assertKeys(root, [...SECTIONS], path, { partial: true })
+ assertKeys(root, [...SECTIONS, 'api'], path, { partial: true })
const defaults = Object.fromEntries(
SECTIONS.map((section) => [section, PARSERS[section](root[section], `${path}: "${section}"`, { partial: false })]),
) as Pick<DeployConfig, (typeof SECTIONS)[number]>
- return { path, root: dirname(path), ...defaults }
+ const config: DeployConfig = { path, root: dirname(path), ...defaults }
+ if ('api' in root) config.api = parseApi(root.api, `${path}: "api"`)
+ return config
}
/**
diff --git a/apps/infra/mdeploy/stack/api.ts b/apps/infra/mdeploy/stack/api.ts
index 31626d800..8306adc92 100644
--- a/apps/infra/mdeploy/stack/api.ts
+++ b/apps/infra/mdeploy/stack/api.ts
@@ -66,6 +66,9 @@ export type ApiCapability =
export { publicHostsFor, type PublicHosts } from './hosts.ts'
export type ApiRequest = {
+ minInstances?: number
+ maxInstances?: number
+ instance?: { cpu: number; memoryMiB: number }
image: $util.Input<string>
port: number
/** The stage's own domain. `publicHostsFor` turns it into the two names served. */
diff --git a/apps/infra/mdeploy/stack/index.ts b/apps/infra/mdeploy/stack/index.ts
index f3d29b131..941629598 100644
--- a/apps/infra/mdeploy/stack/index.ts
+++ b/apps/infra/mdeploy/stack/index.ts
@@ -507,6 +507,7 @@ export const deployStack = ({
waitFor: [...placed, ...database.ready, ...cache.ready, ...collector.ready, ...(mail.sending ? mail.ready : [])],
},
})({
+ ...config.api,
image: imageFor(images, 'api'),
port: API_PORT,
domain: inputs.domain,
diff --git a/apps/infra/mdeploy/stack/providers/gcp/api.ts b/apps/infra/mdeploy/stack/providers/gcp/api.ts
index d87adaa7d..8b54f95d5 100644
--- a/apps/infra/mdeploy/stack/providers/gcp/api.ts
+++ b/apps/infra/mdeploy/stack/providers/gcp/api.ts
@@ -361,7 +361,8 @@ export const gcpApiProvider =
*/
const hosts = publicHostsFor({ domain, dashboardDomain })
const apiHost = hosts.api
- const continuousCi = Boolean(request.environment.CI_GITHUB_APP_CLIENT_ID)
+ const maxInstanceCount = request.maxInstances
+ const minInstanceCount = request.minInstances ?? (request.environment.CI_GITHUB_APP_CLIENT_ID ? 1 : undefined)
const certificateMap = instanceFor({ app: $app.name, stage: $app.stage, artifact: 'proxy' })
const { number: projectNumber } = gcp.organizations.getProjectOutput({ projectId: project })
const role = new gcp.projects.IAMCustomRole('CustomDomainRuntimeRole', {
@@ -481,8 +482,11 @@ export const gcpApiProvider =
// and reads the value held in state — so it refuses the delete half.
// Left on, the first rename of this service costs two applies.
deletionProtection: false,
- ...(continuousCi ? { scaling: { minInstanceCount: 1 } } : {}),
+ ...(minInstanceCount !== undefined || maxInstanceCount !== undefined
+ ? { scaling: { minInstanceCount, ...(maxInstanceCount !== undefined ? { maxInstanceCount } : {}) } }
+ : {}),
template: {
+ ...(maxInstanceCount !== undefined ? { scaling: { maxInstanceCount } } : {}),
serviceAccount: placement.serviceAccount,
/*
* The Cloud SQL proxy the platform builds in, as a volume.
@@ -539,7 +543,12 @@ export const gcpApiProvider =
containers: [
{
image: request.image,
- resources: { cpuIdle: false },
+ resources: {
+ cpuIdle: false,
+ ...(request.instance && {
+ limits: { cpu: String(request.instance.cpu), memory: `${request.instance.memoryMiB}Mi` },
+ }),
+ },
ports: { name: 'http1', containerPort: request.port },
volumeMounts: [
{ name: CLOUD_SQL_VOLUME, mountPath: `/${CLOUD_SQL_VOLUME}` },
diff --git a/apps/infra/mdeploy/test/api-environment.test.ts b/apps/infra/mdeploy/test/api-environment.test.ts
index 046727310..044365ab5 100644
--- a/apps/infra/mdeploy/test/api-environment.test.ts
+++ b/apps/infra/mdeploy/test/api-environment.test.ts
@@ -115,11 +115,14 @@ for (const home of ['aws', 'gcp'] as const) {
}
for (const home of ['aws', 'gcp'] as const) {
- for (const minimum of [undefined, '1', '3', '63']) {
- test(`${home} delivers the platform subdomain minimum ${minimum ?? '(unset)'} from the stage group`, () => {
+ for (const [key, value] of [
+ ['DB_POOL_MAX', undefined],
+ ['DB_POOL_MAX', '25'],
+ ...[undefined, '1', '3', '63'].map((minimum) => ['PLATFORM_SUBDOMAIN_MIN_LENGTH', minimum] as const),
+ ] as const) {
+ test(`${home} delivers ${key} ${value ?? '(unset)'} from the stage group`, () => {
const path = new URL('../../mstage.env.json', import.meta.url)
const declared = parseBase(path.pathname, readFileSync(path, 'utf8'))
- const key = 'PLATFORM_SUBDOMAIN_MIN_LENGTH'
const required = Object.fromEntries(
declared.envSelectGroup
.api!.filter((name) => name !== key && !declared.envOptional.api!.includes(name))
@@ -130,7 +133,7 @@ for (const home of ['aws', 'gcp'] as const) {
groups: declared.envSelectGroup,
optional: declared.envOptional.api,
where: path.pathname,
- values: { ...required, ...(minimum === undefined ? {} : { [key]: minimum }) },
+ values: { ...required, ...(value === undefined ? {} : { [key]: value }) },
})
const { environment, secrets } = apiEnvironmentFrom({
environment: { ...base, ...selected },
@@ -139,8 +142,8 @@ for (const home of ['aws', 'gcp'] as const) {
stage: 'dev',
home,
})
- assert.equal(environment[key], minimum)
- assert.equal(Object.hasOwn(environment, key), minimum !== undefined)
+ assert.equal(environment[key], value)
+ assert.equal(Object.hasOwn(environment, key), value !== undefined)
assert.equal(Object.hasOwn(secrets, key), false)
})
}
diff --git a/apps/infra/mdeploy/test/ci-cloudrun.test.ts b/apps/infra/mdeploy/test/ci-cloudrun.test.ts
index d0bca3239..bbbc2f385 100644
--- a/apps/infra/mdeploy/test/ci-cloudrun.test.ts
+++ b/apps/infra/mdeploy/test/ci-cloudrun.test.ts
@@ -21,7 +21,7 @@ const unwrap = (input: any): any =>
? Object.fromEntries(Object.entries(input).map(([key, item]) => [key, unwrap(item)]))
: input
-function capture(configured: boolean) {
+function capture(configured: boolean, minInstances?: number, instance?: { cpu: number; memoryMiB: number }, maxInstances?: number) {
const records: { type: string; name: string; args: any }[] = []
const namespace = (path: string): any =>
new Proxy(function () {}, {
@@ -127,13 +127,13 @@ function capture(configured: boolean) {
zoneId: 'zone',
network: value('network') as any,
runnerAccount: value('[email protected]') as any,
- })({ ...channels, image: 'registry.example.test/api:fixture', port: 3000, capabilities: [] } as any)
+ })({ ...channels, minInstances, maxInstances, instance, image: 'registry.example.test/api:fixture', port: 3000, capabilities: [] } as any)
const service = records.find((r) => r.type === 'gcp.cloudrunv2.Service' && r.name === 'Api')
assert.ok(service)
return { service: unwrap(service.args), records }
}
-test('the Cloud Run API retains background CPU and adds a service-level minimum only with CI', () => {
+test('the Cloud Run API retains background CPU and uses the hosted CI default when the minimum is omitted', () => {
const on = capture(true).service
assert.deepEqual(on.scaling, { minInstanceCount: 1 })
assert.equal(on.template.containers[0].resources.cpuIdle, false)
@@ -143,6 +143,22 @@ test('the Cloud Run API retains background CPU and adds a service-level minimum
assert.equal(off.template.containers[0].resources.cpuIdle, false)
})
+test('the configured service minimum overrides the hosted CI default', () => {
+ assert.deepEqual(capture(true, 0).service.scaling, { minInstanceCount: 0 })
+ assert.deepEqual(capture(true, 5).service.scaling, { minInstanceCount: 5 })
+ assert.deepEqual(capture(false, 5).service.scaling, { minInstanceCount: 5 })
+ const { service } = capture(true, undefined, undefined, 15)
+ assert.deepEqual(service.scaling, { minInstanceCount: 1, maxInstanceCount: 15 })
+ assert.deepEqual(service.template.scaling, { maxInstanceCount: 15 })
+})
+
+test('Cloud Run receives instance limits only when a stage specifies them', () => {
+ assert.deepEqual(capture(false).service.template.containers[0].resources, { cpuIdle: false })
+ const { service } = capture(false, 5, { cpu: 2, memoryMiB: 2048 })
+ assert.deepEqual(service.template.containers[0].resources, { cpuIdle: false, limits: { cpu: '2', memory: '2048Mi' } })
+ assert.deepEqual(service.scaling, { minInstanceCount: 5 })
+})
+
test('API targeting includes newly configured secret grants absent from the previous state', () => {
const { records } = capture(true)
const service = records.find((record) => record.type === 'gcp.cloudrunv2.Service' && record.name === 'Api')!
diff --git a/apps/infra/mdeploy/test/config.test.ts b/apps/infra/mdeploy/test/config.test.ts
index 4d6e083b7..470e8d010 100644
--- a/apps/infra/mdeploy/test/config.test.ts
+++ b/apps/infra/mdeploy/test/config.test.ts
@@ -28,6 +28,31 @@ const valid = {
const parse = (overrides: Record<string, unknown> = {}) =>
parseDeployConfig('/repo/apps/infra/mdeploy.config.json', JSON.stringify({ ...valid, ...overrides }))
+test('API instance bounds validate configured values and may be omitted', () => {
+ assert.equal(parse().api, undefined)
+ assert.equal(parse({ api: {} }).api?.minInstances, undefined)
+ for (const minInstances of [0, 5]) {
+ assert.equal(parse({ api: { minInstances } }).api?.minInstances, minInstances)
+ }
+ for (const minInstances of [-1, 1.5, '5', null]) {
+ assert.throws(() => parse({ api: { minInstances } }), /minInstances must be a whole number/)
+ }
+ assert.deepEqual(parse({ api: { maxInstances: 15 } }).api, { maxInstances: 15 })
+ assert.throws(() => parse({ api: { maxInstances: 0 } }), /maxInstances/)
+ assert.throws(() => parse({ api: { minInstances: 16, maxInstances: 15 } }), /maxInstances/)
+ assert.throws(() => parse({ api: { minInstance: 5 } }), /does not take minInstance/)
+})
+
+test('API instance sizing validates CPU and memory together', () => {
+ for (const instance of [{ cpu: 1, memoryMiB: 512 }, { cpu: 8, memoryMiB: 32768 }]) {
+ assert.deepEqual(parse({ api: { instance } }).api?.instance, instance)
+ }
+ for (const instance of [{ cpu: 2 }, { memoryMiB: 2048 }, { cpu: 3, memoryMiB: 2048 },
+ { cpu: 1, memoryMiB: 4097 }, { cpu: 4, memoryMiB: 1024 }, { cpu: 2, memoryMiB: '2048' }]) {
+ assert.throws(() => parse({ api: { instance } }), DeployConfigError)
+ }
+})
+
test('runner configuration accepts an optional data disk while preserving required fields and bounds', () => {
assert.deepEqual(parse().runners, valid.runners)
const runners = { ...valid.runners, size: '2xlarge', machineTypes: { medium: 'n4-standard-8', '2xlarge': 'n4d-standard-64' } }
diff --git a/apps/infra/mdeploy/test/stack.test.ts b/apps/infra/mdeploy/test/stack.test.ts
index 1ac881b1a..72ef79b97 100644
--- a/apps/infra/mdeploy/test/stack.test.ts
+++ b/apps/infra/mdeploy/test/stack.test.ts
@@ -329,17 +329,20 @@ test('the runner is placed directly, because it is a machine rather than a task'
assert.ok(seen.runners.input.network, 'it takes its placement from the network instead')
})
-test('the parsed runner data disk size reaches the provider', () => {
+test('parsed stage sizes reach the API and runner providers', () => {
const { providers, seen } = bundle()
const settings = Object.fromEntries(Object.entries(config).filter(([key]) => key !== 'path' && key !== 'root'))
const sizedConfig = parseDeployConfig(
config.path,
JSON.stringify({
...settings,
+ api: { minInstances: 0, instance: { cpu: 2, memoryMiB: 2048 } },
runners: { ...config.runners, dataDiskGb: 2048 },
}),
)
deployStack({ providers, config: sizedConfig, inputs: inputs() })
+ assert.deepEqual(seen.api.request.instance, { cpu: 2, memoryMiB: 2048 })
+ assert.equal(seen.api.request.minInstances, 0)
assert.equal(seen.runners.request.dataDiskGb, 2048)
})
diff --git a/apps/infra/mstage.env.json b/apps/infra/mstage.env.json
index 127551555..9a4a1c160 100644
--- a/apps/infra/mstage.env.json
+++ b/apps/infra/mstage.env.json
@@ -116,6 +116,7 @@
"SMTP_PASSWORD",
"ORGANIZATION_INVITATION_TTL_SECONDS",
"PLATFORM_SUBDOMAIN_MIN_LENGTH",
+ "DB_POOL_MAX",
"CHECKPOINTS_ENABLED",
"FILESTORE_INSTANCES",
"BOXLITE_SYSTEM_SOURCE_REGISTRY_PASSWORD",