RQ

1,032 words5 min read

Moving our CI/CD build machines to EC2 Spot

Spot instances are a natural fit for stateless build machines. The hard part is deciding what happens when AWS takes one back in the middle of a build.

#aws#ci-cd#cost

While I was studying for the AWS Solutions Architect exam, one idea kept coming up: Spot instances are a perfect fit for stateless, fault-tolerant work. They cost much less than On-Demand, and the catch is that AWS can reclaim one at any time with a two-minute notice.

That made me think of our CI/CD pipeline. Every build runs on its own short-lived EC2 machine: it starts, pulls the code, builds one project, uploads the result and shuts down. Nothing on it needs to survive. That’s about as stateless as a workload gets, and we were paying On-Demand prices for all of it.

So I did some research and tried to make the change with as little code as possible. Switching the launch to Spot is the easy part. The real work is having a plan for when a machine is reclaimed halfway through a build.

The basic idea

 request a build machine
          │
    Spot capacity available?
     ├─ yes ──▶ build on a Spot instance
     │              │
     │       interrupted by AWS?
     │        ├─ no  ──▶ build finishes normally
     │        └─ yes ──▶ ask for a retry ──▶ rebuild on On-Demand
     │
     └─ no  ──▶ build on an On-Demand instance

Every build tries Spot first. If AWS has no Spot capacity at launch time, it falls back to On-Demand right away. If a Spot machine is interrupted during the build, the same work is rebuilt on an On-Demand machine, which AWS won’t reclaim.

Noticing the interruption

AWS publishes the interruption notice through the instance metadata service. The build agent starts a small poller as soon as it starts up, before it pulls any code, and checks every 5 seconds:

TOKEN=$(curl -s -X PUT "http://169.254.169.254/latest/api/token" \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 60")
curl -s -o /dev/null -w "%{http_code}" -H "X-aws-ec2-metadata-token: $TOKEN" \
  http://169.254.169.254/latest/meta-data/spot/termination-time
# 404 until AWS decides to reclaim the instance, then 200

When the notice arrives, the agent has about two minutes. It does three things:

  1. Sends a retry message to an SQS queue.
  2. Uploads the partial build log, so the work done so far isn’t lost.
  3. Writes a clear line into the log, so anyone reading it knows the machine was reclaimed and a retry was requested.

A separate service consumes that queue and launches the replacement On-Demand machine.

The rules that made it work

Most of my time went into the state of the build, not the launch. Three rules ended up carrying the whole design.

1. The replacement reuses the original build’s identity. Each build machine has a session ID, and every status row for that build carries it. The replacement is launched with the same session ID, so it reports into the same rows. In the UI, there’s still exactly one result per project: no duplicate entries, and no “interrupted” result sitting next to a “succeeded” one.

2. Read the facts from the database, not from the message. The retry message is small, and it comes from a machine that is about to disappear. So the service only takes the session ID from it, and looks up everything else (environment, build number, version, projects) from the session’s own rows. A malformed or partly empty message still retries correctly.

3. Every row reaches a final status. A build that is “Processing” forever is worse than one that failed, because nobody knows to look at it. If the retry can’t be launched, the rows are closed as failed with a log line that says why. A background cleanup job also closes any row left open past a few hours, as a safety net for cases nothing else catches: a machine lost without a notice, a message lost in transit, or a service restart in the middle of a retry.

The race to watch out for

There’s a subtle race here. After requesting the retry, the dying machine is still running its build, and when it goes down, its normal cleanup path would report the build as Failed. By then, the replacement may already be building. If that Failed status closes the row first, the replacement’s real result is ignored.

So there’s a small guard: once the retry is queued, the interrupted machine skips sending any final status. The replacement owns the build from that point.

The service follows the same idea from the other side. It reopens the rows before it queues the replacement launch, and if the launch can’t be queued, it closes them again. That way a replacement can never be building against a row that has already been marked failed.

Keeping the logs readable

Each attempt uploads its own log file. When the replacement starts, it finds the interrupted attempt’s log and copies it into the top of its own, between two markers:

===== Previous attempt (interrupted) =====
...
===== End of previous attempt; retry on instance i-... =====

When someone opens the log for a build that was retried, they see the whole story in one file: what the first machine did, where it was cut off, and what the replacement did after.

Testing it

The service side is easy to test: put a message on the queue by hand and watch what happens. The agent side, detecting a real notice, can only be tested with a real interruption, or with AWS Fault Injection Service, which can send Spot interruptions on purpose.

In the end, the first real test came from AWS itself. Two days after go-live, a Spot machine was reclaimed in the middle of a build:

Time What happened
0:00 Build starts on a Spot instance
6:12 Interruption notice received; retry requested
6:18 On-demand replacement launched, 6 seconds after the notice
8:10 AWS reclaims the Spot instance
8:40 Replacement starts and copies the earlier log
16:04 Build succeeds; one result in the UI, with the full log

Nobody had to do anything. That was the goal.

What I’d still improve

  • Spread across Availability Zones. All build machines launch into a single subnet, so one capacity event can reclaim every machine in a build at once. That has already happened. More AZs and more instance types would make that much less likely.
  • One retry only. The replacement runs On-Demand and isn’t retried again. That’s on purpose, but it means a failure on the replacement fails the build normally.
  • Test interruptions on purpose. Running AWS Fault Injection Service regularly would mean I don’t have to wait for AWS to test the agent side for me.

Looking back, the change itself was small. Most of the effort went into one question: if this machine disappears right now, what state does it leave behind, and who cleans it up? Once that had a clear answer for every step, Spot was simply a cheaper way to run the same builds.

← All writing