# Self-hosted runners, one deployment per product

> Auto-scaling GitHub Actions runners on EC2 spot, deployed once per product so a slow test suite in one place cannot starve a deploy somewhere else. What it cost us, and what I still had to own.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2022-09-17
- URL: https://deyanpeev.com/posts/self-hosted-runners-one-deployment-per-product

Six months ago I wrote that managed runners were the bigger saving in
[GitHub Actions over Jenkins](https://deyanpeev.com/posts/github-actions-over-jenkins), and for a
new repository I still think that. This post is the other half of that
sentence. We outgrew hosted runners and moved everything onto our own machines,
and it was bearable because Terraform owned the machines and not a person.

We left the hosted fleet because builds needed to reach a database that has no
public address, and because some jobs wanted more memory than the standard
hosted runner offers. Also the minutes had stopped being background noise on
the invoice.

What replaced it is the
[terraform-aws-github-runner](https://github.com/github-aws-runners/terraform-aws-github-runner)
module. It's a set of Lambda functions that watch GitHub for queued jobs, start
EC2 spot instances to run them, and terminate the instances when the work is
done. All of our CI and CD sits on it and the bill lands between $150 and $200
a month.

# How the module works

Nothing in this module runs continuously except the Lambdas, and Lambdas that
aren't invoked cost nothing.

A workflow job is queued. GitHub sends a `workflow_job` event to a webhook,
which is an API Gateway endpoint in front of a Lambda. That Lambda verifies the
signature, decides whether the event is one it cares about, and posts it to an
SQS queue. The queue holds the message for a configurable delay (thirty seconds
by default), so that a runner that's already running has a chance to pick the
job up before anything new is started.

The scale-up Lambda reads the queue. It checks whether the job has already been
claimed and whether the deployment is at its ceiling, requests a runner
registration token from GitHub, writes that token into SSM Parameter Store, and
launches a spot instance from a launch template. The instance's user data pulls
the token out of Parameter Store, deletes it, installs the runner, and registers.

A separate scale-down Lambda runs on a schedule, every five minutes by default.
It walks the instances and terminates the ones that are not busy, deregistering
them from GitHub on the way out. So it's a poll, there is no signal, and the
module's own documentation is candid that this is brute force.

There's one more Lambda, and it looks like an odd inclusion until you hit the
problem it solves. Downloading the runner distribution from GitHub is
occasionally very slow, as in minutes. So a syncer copies the release into an
S3 bucket on a schedule, and instances fetch it from there.

The [getting-started guide](https://github-aws-runners.github.io/terraform-aws-github-runner/getting-started/)
walks the setup in three phases. You create a GitHub App, apply the Terraform,
then come back and point a webhook at the API Gateway URL that Terraform
printed. You can't avoid the two passes, because each side needs an output from
the other.

# One deployment, and why that was not enough

The first version was a single deployment for the whole organisation. It
worked, and it was wrong within a fortnight.

Every queued job in every repository goes onto one SQS queue and competes for
one `runners_maximum_count`. One product's integration suite fans out into a
wide matrix, saturates the ceiling, and a one-job deploy for an unrelated
service sits behind it. Raising the ceiling raises it for everyone, including
the workload that was already the problem, so the fix is a separate queue.

So we stopped deploying the module once and deployed it once per product. Each
one has its own prefix, webhook, queue, ceiling and label.

```hcl
module "runners_billing" {
  source  = "philips-labs/github-runner/aws"
  version = "1.9.0"

  aws_region = local.aws_region
  vpc_id     = module.vpc.vpc_id
  subnet_ids = module.vpc.private_subnets

  prefix = "ci-billing"
  tags   = { Product = "billing" }

  github_app = {
    id             = var.github_app_id
    key_base64     = var.github_app_key_base64
    webhook_secret = random_id.billing_webhook_secret.hex
  }

  webhook_lambda_zip                = "lambdas-download/webhook.zip"
  runners_lambda_zip                = "lambdas-download/runners.zip"
  runner_binaries_syncer_lambda_zip = "lambdas-download/runner-binaries-syncer.zip"

  enable_organization_runners = true
  runner_extra_labels         = "billing"

  runner_enable_workflow_job_labels_check     = true
  runner_enable_workflow_job_labels_check_all = true

  instance_types                = ["m5.large", "m5a.large", "c5.large"]
  instance_target_capacity_type = "spot"
  instance_allocation_strategy  = "capacity-optimized"

  runners_maximum_count           = 8
  minimum_running_time_in_minutes = 5
  delay_webhook_event             = 10
}
```

A second module block, `runners_search`, is the same thing with
`prefix = "ci-search"`, `runner_extra_labels = "search"`, and whatever ceiling
that product's builds need. The blocks are boring and nearly identical. What
matters is that they don't share a queue.

The workflow asks for its own product's runners by label:

```yaml
jobs:
  test:
    runs-on: [self-hosted, linux, x64, billing]
```

Sizing is per product too. The service with a heavy test suite got larger
instance types and a ceiling of sixteen. A service whose pipeline is a lint,
a unit run and a container push got two `t3.medium`s and never noticed.
With one deployment those two would have had to share the same settings.

# The label check is not optional here

I would have got this wrong if I hadn't read the variable descriptions, and it
decides whether the arrangement above works or turns into an expensive mess.

We used one organisation-level GitHub App for the API credentials, and a
separate organisation webhook per deployment, each pointed at its own API
Gateway URL with its own secret. GitHub does not route between them. Every
`workflow_job` event goes to *every* webhook, so each deployment's webhook
Lambda sees the billing job, the search job and everything else.

By default the module accepts those events. Every deployment would start an
instance for every queued job, and the label the job asked for would only be
consulted later, when the runners tried to claim work. You'd pay for six
fleets to answer one job and then watch five of them idle until the scale-down
poll came round.

`runner_enable_workflow_job_labels_check` moves that decision to the webhook.
With it on, the Lambda compares the labels on the event against the labels this
deployment's runners will carry (`self-hosted`, the OS, the architecture, plus
whatever is in `runner_extra_labels`) and drops the event if they don't line
up.

`runner_enable_workflow_job_labels_check_all` decides how strict that comparison
is. It defaults to true, and true is what you want, meaning *every* label on
the job must be one this deployment offers. Set it to false and a match on any
single label is enough. Then `self-hosted`, a label every one of these jobs
carries, matches every deployment, and you are back to the fan-out. I set both
explicitly even though the default is fine, because a correct default doesn't
tell the next person that it matters.

`repository_white_list` is the belt to that pair of braces. Naming the
repositories a deployment is allowed to serve means a mislabelled workflow in
some other repository can't start machines on the billing product's budget.

# What scaling to zero costs

The runners scale to zero but the infrastructure around them doesn't. Our
floor was the plumbing: NAT gateways so instances in private subnets can reach
GitHub and S3, API Gateway, the Lambdas, the S3 bucket holding the runner
distribution, Parameter Store, and log retention. A NAT gateway is charged by
the hour whether or not anything is behind it. That works out to roughly $30 a
month each before data processing, and it was comfortably the largest line that
did not move. Everything else in that list was cents. Roughly half of our
monthly total was this floor, and it would have been the same on a month with no
builds at all.

The other half tracked build minutes, and spot is what kept that half small.
`instance_target_capacity_type = "spot"` with `capacity-optimized` allocation
across three instance types meant we very rarely paid on-demand and very rarely
got interrupted. Call it $90 a month of compute at spot rates for an
`m5.large`-shaped fleet, so somewhere around two thousand runner-hours.

Two thousand hours of the same work on GitHub-hosted Linux runners, at $0.008
per minute past the included allowance, is a little over a thousand dollars. At
this volume it isn't close.

The comparison flatters us slightly. Hosted minutes are billed per job, rounded
up. Our instance-hours include the boot, and they include however long a runner
sat idle before the five-minute scale-down poll found it.
`minimum_running_time_in_minutes` makes that worse, intentionally, in exchange
for reusing a warm machine. The true ratio is less than ten to one, but it was
still not close.

The line that surprised me was CloudWatch Logs. Streaming runner logs off the
instances is useful when a build fails on a machine that no longer exists. It's
also the one component whose cost scales with how chatty your builds are and
not with how long they run. Setting a retention period was a one-line fix, and
I shouldn't have needed prompting to make it.

# What I still own

Terraform owning the fleet still left us with all of this.

Jobs start slower. A cold runner is an EC2 launch, a user-data script and a
registration, so a couple of minutes before the first line of the build.
`delay_webhook_event` adds to it intentionally, so an already-running runner
gets first refusal. Where the wait mattered we used `idle_config` to keep a
small warm floor during working hours. That's a direct trade of money for
latency, and it should be something you decide and not something you get by
leaving the default.

The image drifts too. The default Amazon Linux 2 AMI plus a user-data script is
a fine starting point and a slow one, because every instance installs the same
things again. Baking a prebuilt AMI moves that work to build time. It also means
you now maintain an AMI pipeline, and that work didn't exist when GitHub owned
the machines.

You also have to choose between reusable and ephemeral runners. Reusable
runners take one job after another until they go idle. That's fast, and it
means one job can leave state behind for the next. Ephemeral runners are
destroyed after a single job, so they are clean and they pay the boot cost
every time. We kept reusable runners where builds were frequent and cheap, and
used ephemeral ones where a job handled deployment credentials. That split was
worth the extra deployment.

Public repositories are off the table. A self-hosted runner will happily execute
whatever a pull request tells it to, and on a public repository that's a
stranger's code running inside your VPC. Everything on this fleet was private,
and I would not relax that for convenience.

Spot instances go away. Rarely, with the diversified instance types, but it
happens, and the job dies with the machine. Anything long enough for that to
sting needs to be retryable.

# Where I would still not do this

I wouldn't do any of the above for a repository with a five-minute build. The
included allowance covers it, the hosted runner is already patched, and the
fixed floor here costs more per month than the minutes ever would. There is a
crossover point but it's nowhere near zero.

For us it was worth it because of what the workload looked like and not only
how big it was. We had a set of products, deploying independently, on a network
the hosted runners cannot see. And once you're on your own machines anyway,
giving each product its own queue and its own ceiling costs one more module
block, and it gets rid of the complaints about someone else's tests holding up
your release.

---

*The module has since moved to the `github-aws-runners` organisation, and its
Terraform registry path with it. The links above point at its current home; the
`source` in the example is the one that was correct at the time of writing.*
