Skip to content

7g. Worker scaler (0.46.0)

Adding and removing worker machines leaves the buying and the deleting to you. The scaler is an optional control-stack service that does it: it creates a worker through OpenTofu when previews do not fit, and drains and destroys one it created after it has sat empty. Swarm only. With it off, nothing in this section exists on the host.

Not captured here: every step needs a real cloud account. Commands and routes are the shipped ones.

Terminal window
pstack init … --scaler on # a new host; or PSTACK_SCALER=on
pstack cloud-init … --scaler on # passed to init on first boot

On a host that already runs, re-run pstack init with the flags it was installed with plus --scaler on. init refuses --scaler on with --orchestrator compose (exit 3) before it changes anything. pstack upgrade, pstack ui and pstack logging keep the scaler; an init without --scaler on on a host that has one is refused (--scaler on to keep it, --scaler off to remove it). Turning it off destroys nothing: the workers it owns keep running and stay on the card.

init adds a scaler service to the control stack: the same image as pstack, command pstack scaler, no ports, no docker socket, stop_grace_period: 5m, and one volume, <PSTACK_DATA>/scaler → /state (0700). It talks to pstack at http://pstack:7878 on a private scaler network that only the two of them join, with the host’s root token. On first start it downloads OpenTofu 1.13.9 into /state/bin, checked against a pinned sha256 (amd64 and arm64).

Settings and credentials go in afterwards, never in instance user-data: the Workers card on the Control page (both UIs), or PUT /api/scaler. The scaler reads them every 30 s, so a save needs no restart.

{
"preset": "hetzner",
"vars": { "server_type": "cx32", "location": "fsn1", "ssh_keys": "[\"ops\"]" },
"min": 0, "max": 3, "cooldownMin": 5, "graceMin": 15,
"credentials": { "HCLOUD_TOKEN": "…" }
}
Terminal window
H="Authorization: Bearer $PSTACK_TOKEN" # admin to write, maintainer to read
curl -X PUT -H "$H" https://api.<domain>/api/scaler -d @scaler.json # a file: argv is world-readable

A PUT replaces every setting; an absent one takes its default (min 0, max 3, cooldownMin 5, graceMin 15). Variable values are strings; one starting with [ or { reaches Tofu as JSON. A credential goes in and never comes back out: GET /api/scaler answers {"HCLOUD_TOKEN": true}. Sent empty, omitted or as the mask, a credential keeps its stored value; null deletes it. pull config does not carry any of it (scaler: host-specific — re-enter it on the target).

A preset is a folder of .tf files. Five are built in, read-only, embedded in the binary and in the repository at packages/pstack/internal/scaler/presets/<name>/. Each pins its provider with a lock file for linux amd64 and arm64, and boots amd64 images (an Arm machine type needs a custom preset).

Preset Per worker Shared Credential Firewall it creates
hetzner (Debian 12) server_type, location manager_address*, ssh_keys, network_id (optional) HCLOUD_TOKEN One hcloud_firewall applied by the label pstack-scaler=<host_id>: 2377/tcp, 7946 tcp/udp, 4789/udp from the manager and the workers, 22 from anywhere, all outbound.
aws (Ubuntu LTS) instance_type region, subnet_id (the manager’s VPC), key_name (optional) AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY One security group: 7946 tcp/udp and 4789/udp from every CIDR block of the VPC and from itself; all outbound.
gcp (Ubuntu LTS) machine_type, zone project, subnetwork (the manager’s) GOOGLE_CREDENTIALS (service-account JSON) One rule on the subnetwork’s network: the swarm ports from its range to the workers.
azure (Ubuntu LTS) vm_size resource_group, location, subnet_id (the manager’s VNet), admin_ssh_public_key ARM_CLIENT_ID, ARM_CLIENT_SECRET, ARM_TENANT_ID, ARM_SUBSCRIPTION_ID None: AllowVnetInBound admits the VNet.
digitalocean (Ubuntu LTS) size, region manager_address*, ssh_keys, vpc_uuid (optional) DIGITALOCEAN_TOKEN One digitalocean_firewall on the tag pstack-scaler-<host_id>: the swarm ports from the manager and that tag, 22 from anywhere, all outbound.

* Filled by the scaler from the manager’s swarm advertise address; you never set it. host_id (8 hex characters, generated once, shown on the card) is filled the same way. Every server carries the label pstack-scaler=<host_id>, or on DigitalOcean the tags pstack-scaler-<host_id> and pstack-scaler-<host_id>:<name>, so you can find it in the provider’s console. Two pstack hosts in one cloud project never touch each other’s workers.

Custom presets: PUT /api/scaler/presets/<name> with { "files": { "main.tf": "…" } } (admin); list, read and delete the same way. The contract:

  • variable "workers" of type map(object({ user_data = string, … })). Its other attributes are the per-worker variables; every other variable is shared. manager_address and host_id are filled when declared.
  • One server per entry (for_each = var.workers), named after the key, carrying the label or tags above, with lifecycle { ignore_changes = [...] } naming the user-data attribute and the image. Otherwise every upgrade, join-token rotation or new image rebuilds every worker.
  • A firewall it creates allows all outbound traffic: a worker must reach the manager’s 2377, the Docker repository and the registries before it can join.
  • Credentials come from the provider’s own environment variables.
  • No backend or cloud block: state is local, in /state/tofu/<preset>/.
  • # pstack-distro: <distro> in any file picks the join cloud-config’s distro (default ubuntu).
  • Files are *.tf and .terraform.lock.hcl. Without a lock file providers download unpinned; the card says so.

A custom preset is code. Tofu runs it with the root token and the cloud credentials in reach; tofu validate is not a sandbox. Uploading one is admin-only, the same trust as a spec’s hooks.

A worker must reach the manager at its advertise address, and the manager must reach the worker at the address the worker advertises. So a worker goes on the manager’s provider and, where the provider puts only a private address on the interface (AWS, GCP, Azure), in the manager’s private network: subnet_id or subnetwork is the manager’s. Workers on another provider are not supported.

On Hetzner and DigitalOcean a server carries its public address, so a manager advertising its public address works anywhere on that provider (the overlay is unencrypted on the provider’s network, as for a worker you join by hand). network_id (a Hetzner Cloud Network) or vpc_uuid (a DigitalOcean VPC) puts workers in the manager’s private network instead; a manager advertising a private address needs it, and the scaler refuses without it. The manager must advertise an IPv4 address.

The manager’s own firewall must let workers in: 2377/tcp, 7946/tcp+udp and 4789/udp. Where workers have a range (a VPC, a subnet, a private network), allow that range. On Hetzner and DigitalOcean with public addresses there is no range: put the manager under the preset’s firewall with the label pstack-scaler=<host_id> (Hetzner) or the tag pstack-scaler-<host_id> (DigitalOcean). Both providers add the rules of every firewall that applies.

Before you label or tag the manager, give it a firewall of its own that admits its public ports: 80 and 443, and 22 if you use it. Once any firewall applies to a server, every inbound port no firewall names is denied, so a manager under the preset’s firewall alone stops serving previews.

Every 30 s, at most one action, one Tofu command at a time:

  • Adds a worker when owned workers are below min, or when a task is stuck with a reason a machine can fix: no suitable node (…) whose every clause is insufficient resources on N nodes or a drained node. Not while another worker is booting, within cooldown of the last one, at max, or while an owned worker with the current settings is ready and empty. A reason with any other clause (scheduling constraints not satisfied) adds nothing.
  • Removes a worker that has been ready, active and empty for grace, when owned workers are above min, in this order: drain → tofu apply without it → wait for its node to be down → DELETE the node. A worker whose settings differ from the current ones goes when empty whatever min says, so a changed server type replaces the fleet as workers empty.
  • max: 0 removes every owned worker, one per tick, without waiting for grace. Draining evicts their tasks; previews with no room elsewhere go pending.
  • A worker not ready 10 minutes after its apply never joined: it is removed and counts. After two in a row it adds none until you change the settings.
  • A new worker that leaves its services stuck marks them does not fit until the settings change: a same-size machine would not fit them either.
  • A failed apply retries with backoff (1, 2, 4 … 30 min), kept across restarts.
  • A server deleted in the console, or a node not ready for 10 minutes, is removed and never recreated under its old name.

It acts only on workers it created, by name, and only on nodes whose role is worker. A manager, or a worker you joined by hand, is never touched. Signals unreadable, swarm down, no preset, or a preset that fails tofu validate: no action, no clock advances, the reason on the card. The scaler cannot tell which credentials a preset needs, so a missing one shows as a failed refresh or apply.

Reservations decide load-based scaling. Swarm reports insufficient resources only against reservations, so past min the scaler adds workers for load only when previews declare deploy.resources.reservations (or mem_reservation). A cluster with no node previews may use (the manager labelled off by --previews-on workers, min: 0) still gets its first worker: a drained node qualifies, and so do placement constraints that no more nodes fail than there are managers.

Settings are frozen per worker. A worker keeps the per-worker variables it was created with, so an edit changes only workers created afterwards. While the scaler owns any worker, the preset and its shared variables are locked: PUT /api/scaler and the preset routes answer 409. To switch preset: max: 0, wait for zero workers, then switch. The scaler then runs tofu destroy on the old preset’s shared resources. Credential keys cannot be deleted while it owns workers or that destroy is pending.

After an unclean stop (a reboot, a kill past the 5-minute grace) Tofu may have created a server it did not record. The scaler lists the name as a possible orphan on the card, never creates it again, and emits scaler.failed with action: orphan, then scaler.removed with reason orphan once it drops the worker record. Tofu has no record of that server, so look for the name and the label in the provider’s console, delete it there if it exists, then Dismiss it on the card.

On the Control page while the scaler runs or still owns workers: the preset and its variables, min/max/cooldown/grace, the credential keys (write-only, admin), host_id, each owned worker with its settings and state (booting, ready, down, lost, removing), the last action and error, the next retry, services that do not fit, possible orphans, and a pending old-preset destroy. Custom presets are edited there too.

Events: scaler.created, scaler.removed, scaler.failed (webhook-events.md). None carries a credential, the join token or user_data; Tofu’s output is scrubbed, then cut to its last 20 lines. scaler.removed reasons: empty, replaced, max, lost, never-joined, orphan.

Nothing here is needed to scale workers another way. Signals, signal.raised/signal.cleared, the drain, undrain and remove routes and /api/swarm/join behave the same with the scaler on or off. The built-in presets are plain folders: tofu apply with a workers.auto.tfvars.json works without pstack. Two rules:

  • Run it outside the pstack-control compose project. init, upgrade, pstack ui and pstack logging run up --remove-orphans, which deletes containers in that project that pstack did not render.
  • Don’t run two scalers on one host unless they own disjoint workers. The built-in one touches only names it created, but two policies reacting to the same stuck task both add a machine.