One afternoon ten CI jobs queued within a second of each other, and four of them started three minutes late. EC2 had capacity for all ten the whole time.
This is the third of five posts about running each GitHub Actions job on its own EC2 spot instance. The first post covers the design. This one is about the single API call the whole system depends on, RunInstances, and the two bugs that taught us where a retry belongs.
The version that almost worked
A job chooses a pool with a label, and a pool is a list of three instance types, newest generation first. To launch, we try each type in each of three availability zones on the spot market, then the same nine combinations on demand. Eighteen tries at most, and most of the time the first one succeeds.
A pull request on our largest repository queues ten or more jobs at once. Ten workers call RunInstances in the same second, and EC2 throttles the API past a few calls per second. The AWS SDK retries a throttled call by itself, three attempts by default, and gives up after about 160 milliseconds. That was not enough, so we did the obvious thing and raised it to eight attempts, which back off for up to 25 seconds.
That change is where both bugs come from.
Bug 1: the retry we did not know we had
The next burst arrived when the newest instance type had no spot capacity. Half the workers ran for 60 seconds, hit the Lambda timeout, and launched nothing. Their jobs waited five to ten minutes for the reaper, the scheduled function that sweeps up stuck jobs.
The walk should have handled it: no capacity here, try the next cell, a second at most. CloudTrail said otherwise. For 30 tries made by our code, EC2 had logged 144 InsufficientInstanceCapacity errors.
EC2 returns that error with HTTP status 500. To the SDK, a 500 is a transient server fault, and transient faults get retried. Every cell our loop tried once, the SDK tried eight times with backoff, 15 to 30 seconds per cell. Three cells without capacity used up the whole minute.
The timeout made it worse. A worker claims a job before it launches and releases the claim if the launch fails. A Lambda that times out runs no cleanup, so the claim stayed. Lambda retried the event twice, and both retries found the job already claimed and did nothing.
The fix was to tell the SDK what we meant:
export class ThrottlingOnlyRetryStrategy extends StandardRetryStrategy {
override async refreshRetryTokenForRetry(
token: StandardRetryToken,
errorInfo: RetryErrorInfo
): Promise<StandardRetryToken> {
if (errorInfo.errorType !== 'THROTTLING') {
throw new ServiceUnavailable('Not retried', {errorType: errorInfo.errorType});
}
return super.refreshRetryTokenForRetry(token, errorInfo);
}
}
The SDK retries throttling and nothing else. For a capacity error, the next cell is the retry.
Bug 2: the retry we gave up on
We deployed that and watched the next burst. This is the one from the opening: ten jobs, four of them late by two and a half to four minutes. CloudTrail for those six minutes showed 60 launch calls: 16 succeeded, 24 failed on capacity, 20 were throttled.
Capacity was not the problem this time. One zone had room, and every worker that reached it launched. The problem was the 20 throttles. A call that was still throttled after the SDK's eight attempts came back to our loop as an error, and our loop knew two kinds of error: "no capacity, try the next cell" and "anything else, give up". Throttling was anything else.
Giving up was handled correctly, which is what made it slow. The worker released the claim and threw. Lambda retries a failed asynchronous event after about one minute, then after two. So a job that lost the throttling lottery started one to three minutes late, by design of the retry schedule of a system that did not know what it was retrying.
The loop now owns the throttle:
const throttleDeadline = Date.now() + THROTTLE_BUDGET_MS; // 40 s
for (const market of ['spot', 'on-demand'] as const) {
tries: for (const instanceType of pool.instanceTypes) {
for (const subnet of runnerConfig().subnets) {
for (;;) {
try {
const instance = await runOnce(pool, {instanceType, subnet, market, userData, tags});
if (instance?.InstanceId) return {instance, instanceType, market};
break;
} catch (e) {
const code = errorCode(e);
if (code === THROTTLE_ERROR && Date.now() < throttleDeadline) {
await throttlePause(); // 1 to 2 s, with jitter
continue; // the same cell again
}
if (market === 'spot' && code === SPOT_LIMIT_ERROR) break tries;
if (!NEXT_TRY_ERRORS.has(code)) throw e;
break; // the next cell
}
}
}
}
}
A throttled cell is tried again after a short pause, until 40 seconds have passed since the walk began. The SDK's own attempts went back down to three. Past the budget the error is thrown as before, and the claim is released. The budget is a cutoff for starting another try, not a hard limit: a call that begins just before it can run a few seconds past. That is why it is 40 seconds and not 55. The function times out at 60, and a timeout is the one exit that skips the release.
The four answers
| EC2 says | It means | The walk does |
|---|---|---|
InsufficientInstanceCapacity |
no spot of this type in this zone | the next cell |
MaxSpotInstanceCountExceeded |
the account's spot limit | skip to on demand |
RequestLimitExceeded |
too many API calls right now | the same cell again, within 40 s |
| anything else | a real error, such as a vCPU quota | stop, release the claim, throw |
Each row is a different decision about the next try. That is why the SDK could not make it for us: it sees a status code, and only the loop knows that the right answer to "no capacity" is a different zone and the right answer to "slow down" is the same call a second later.
The walk got a real test the same afternoon. Eighteen minutes after the first fix was deployed, the newest instance type ran out of spot capacity, and every launch for the rest of the day fell back to the previous generation. No job was late for it. We noticed only because a benchmark we were running came out about 15 % slower, and the job logs showed the older instance type.
What it does not do
- It waits throttling out. It does not avoid it. Ten workers still call EC2 in the same second. A stagger across workers, or one launcher that batches, would reduce the throttling itself. We have not built either, because the wait is now bounded and short.
- It does not go down a size. When a pool has no capacity on any type, the job goes on demand at the size its author asked for. Running it on a smaller machine would be faster to start and slower to finish, and hard to explain in a job log.
- It does not predict. We do not track capacity or pick zones by recent success. The error from the next call is the signal, and it is exact.
What we took from it
- Retries belong in one place, with one time budget. A retry inside a library spends the budget of the loop above it, and the loop cannot see it happen. We turned the SDK's retries down, not up.
- Read what your error codes mean to the layer below. A capacity error that is a 500 is a transient fault to an SDK and a routing decision to us.
- Know which exit skips your cleanup. For a Lambda it is the timeout, so every budget has to end before it.

Top comments (0)