DEV Community

Florient DOGBE
Florient DOGBE

Posted on

Spot Instances Without Drama: Interruption Notices, Proactive Drain, and Checkpointing Batch Workloads

Spot (AWS), preemptible/Spot VMs (GCP, Azure) instances cut compute bills by 60–90%. The catch is simple and brutal: the cloud provider can take the node back at any time, and you get a very short warning — 2 minutes on AWS EC2 Spot, 30 seconds on GCP preemptible VMs and Azure Spot. Teams that treat spot as "cheap on-demand" discover the hard way that a 6-hour batch job with no checkpoint is a 6-hour job that never finishes.

The good news: on Kubernetes and OpenShift, the engineering work to make spot boring is mostly plumbing you can do in an afternoon. This article walks through the full chain: node pool partitioning with taints and labels, wiring an interruption handler, writing batch workloads that survive a SIGTERM mid-flight, and — the part everybody skips — measuring the real failure rate instead of guessing.

What you are actually buying with spot capacity

A spot instance is spare capacity the provider reclaims when demand rises or when your bid is outpriced. Interruption rates are not uniform: they depend on instance type, availability zone, and time of day. Within the same region, m5.large in eu-west-1a and m6i.4xlarge in eu-west-1c can have wildly different reclaim frequencies. AWS publishes a Spot placement score and interruption frequency ranges, but the only number that matters for your SLOs is the one you measure in your own cluster.

Three workload classes map well to spot:

  • Stateless HTTP services with more than one replica, a correct readiness probe, and a load balancer that drains connections.
  • Batch and queue consumers that process discrete units of work and can replay a unit.
  • CI runners and ephemeral build agents, where a failed build is simply retried.

Three that do not: single-replica stateful databases, workloads with locally attached state and no replication, and anything with a hard "exactly once, no retry" contract at the pod level.

The interruption signal and its real budget

On AWS, the instance metadata service (IMDS) exposes two distinct signals:

  • /latest/meta-data/events/recommendations/rebalance — rebalance recommendation, emitted when the instance is at elevated risk. It can arrive minutes before the actual notice, sometimes not at all.
  • /latest/meta-data/spot/instance-action — the 2-minute interruption notice. After this, termination is guaranteed.

Query it from a node (IMDSv2 requires a token):

TOKEN=$(curl -sX PUT "http://169.254.169.254/latest/api/token" \
  -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")

curl -s -H "X-aws-ec2-metadata-token: $TOKEN" \
  -w '\nHTTP %{http_code}\n' \
  http://169.254.169.254/latest/meta-data/spot/instance-action
# HTTP 404 while the instance is healthy
# {"action":"terminate","time":"2024-05-21T14:32:00Z"} once notified
Enter fullscreen mode Exit fullscreen mode

Budget those 120 seconds honestly. A realistic split: ~5s for detection polling, ~10s for cordon + eviction API calls, which leaves roughly 90–100 seconds of usable terminationGracePeriodSeconds. If your pod needs 3 minutes to flush state, spot is not your problem — your shutdown path is.

Partition the cluster: spot pools, taints, and labels

Never mix spot and on-demand capacity in a single undifferentiated pool. You want explicit opt-in: a workload lands on spot because someone declared it can tolerate interruption.

An OpenShift MachineSet for spot

On OpenShift with the Machine API on AWS, spot is one field in providerSpec, plus node labels and taints propagated from the Machine template:

apiVersion: machine.openshift.io/v1beta1
kind: MachineSet
metadata:
  name: ocp-cluster-abc12-spot-eu-west-1a
  namespace: openshift-machine-api
  labels:
    machine.openshift.io/cluster-api-cluster: ocp-cluster-abc12
spec:
  replicas: 3
  selector:
    matchLabels:
      machine.openshift.io/cluster-api-cluster: ocp-cluster-abc12
      machine.openshift.io/cluster-api-machineset: ocp-cluster-abc12-spot-eu-west-1a
  template:
    metadata:
      labels:
        machine.openshift.io/cluster-api-cluster: ocp-cluster-abc12
        machine.openshift.io/cluster-api-machine-role: worker
        machine.openshift.io/cluster-api-machine-type: worker
        machine.openshift.io/cluster-api-machineset: ocp-cluster-abc12-spot-eu-west-1a
    spec:
      metadata:
        labels:
          node-role.kubernetes.io/worker: ""
          capacity-type: spot
      taints:
        - key: capacity-type
          value: spot
          effect: NoSchedule
      providerSpec:
        value:
          apiVersion: machine.openshift.io/v1beta1
          kind: AWSMachineProviderConfig
          instanceType: m6i.2xlarge
          placement:
            region: eu-west-1
            availabilityZone: eu-west-1a
          spotMarketOptions: {}          # <- empty = spot at the on-demand cap price
          ami:
            id: ami-0123456789abcdef0
          iamInstanceProfile:
            id: ocp-cluster-abc12-worker-profile
          securityGroups:
            - filters:
                - name: tag:Name
                  values: [ocp-cluster-abc12-worker-sg]
          subnet:
            filters:
              - name: tag:Name
                values: [ocp-cluster-abc12-private-eu-west-1a]
          userDataSecret:
            name: worker-user-data
          credentialsSecret:
            name: aws-cloud-credentials
Enter fullscreen mode Exit fullscreen mode

Create one MachineSet per AZ and per instance type family. Capacity pools are per (type, AZ); spreading across three types and three AZs turns a single reclaim event from "the batch pool is gone" into "a third of one pool is gone".

oc -n openshift-machine-api get machinesets
oc -n openshift-machine-api get machines \
  -l machine.openshift.io/interruptible-instance= \
  -o custom-columns=NAME:.metadata.name,STATE:.status.phase,NODE:.status.nodeRef.name
Enter fullscreen mode Exit fullscreen mode

That machine.openshift.io/interruptible-instance label is set by the Machine API on spot machines — a free inventory of your interruptible fleet.

On vanilla EKS with Karpenter, the equivalent is a NodePool with karpenter.sh/capacity-type: ["spot"] and a broad node.kubernetes.io/instance-type requirement list; Karpenter already consumes interruption events from an SQS queue, which replaces part of what follows.

Scheduling rules for workloads

With a NoSchedule taint on spot nodes, nothing lands there by accident. Opt in explicitly with tolerations + nodeSelector, and keep replicas spread:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: thumbnailer
  namespace: media
spec:
  replicas: 6
  selector:
    matchLabels: {app: thumbnailer}
  template:
    metadata:
      labels: {app: thumbnailer}
    spec:
      nodeSelector:
        capacity-type: spot
      tolerations:
        - key: capacity-type
          operator: Equal
          value: spot
          effect: NoSchedule
      topologySpreadConstraints:
        - maxSkew: 1
          topologyKey: topology.kubernetes.io/zone
          whenUnsatisfiable: ScheduleAnyway
          labelSelector:
            matchLabels: {app: thumbnailer}
        - maxSkew: 1
          topologyKey: kubernetes.io/hostname
          whenUnsatisfiable: ScheduleAnyway
          labelSelector:
            matchLabels: {app: thumbnailer}
      terminationGracePeriodSeconds: 90
      containers:
        - name: app
          image: quay.io/acme/thumbnailer:1.8.3
          lifecycle:
            preStop:
              exec:
                command: ["/bin/sh", "-c", "sleep 10"]   # let endpoints converge
          resources:
            requests: {cpu: "500m", memory: 512Mi}
            limits: {memory: 1Gi}
Enter fullscreen mode Exit fullscreen mode

A PodDisruptionBudget is what makes the drain safe rather than destructive. Use maxUnavailable for stateless fleets so it scales with replica count:

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: thumbnailer
  namespace: media
spec:
  maxUnavailable: 25%
  selector:
    matchLabels: {app: thumbnailer}
Enter fullscreen mode Exit fullscreen mode

Caution: a PDB that can never be satisfied (e.g. minAvailable: 1 on a single-replica Deployment) will block eviction, the handler will spin until the 120s expire, and the pod gets killed anyway — with zero grace. PDBs are a coordination mechanism, not a shield against the hypervisor.

Wiring the interruption handler

aws-node-termination-handler (NTH) is the reference implementation. Two modes:

IMDS mode — a DaemonSet on spot nodes

Each pod polls the local IMDS endpoint. No IAM permissions, no extra AWS infrastructure. Restrict it to spot nodes and make sure it tolerates your taint:

helm repo add eks https://aws.github.io/eks-charts
helm repo update

helm upgrade --install aws-node-termination-handler eks/aws-node-termination-handler \
  --namespace kube-system \
  --set enableSqsTerminationDraining=false \
  --set enableSpotInterruptionDraining=true \
  --set enableRebalanceMonitoring=true \
  --set enableRebalanceDraining=true \
  --set enableScheduledEventDraining=true \
  --set taintNode=true \
  --set emitKubernetesEvents=true \
  --set podTerminationGracePeriod=90 \
  --set nodeTerminationGracePeriod=120 \
  --set enablePrometheusServer=true \
  --set nodeSelector."capacity-type"=spot \
  --set-json 'tolerations=[{"key":"capacity-type","operator":"Equal","value":"spot","effect":"NoSchedule"}]'
Enter fullscreen mode Exit fullscreen mode

What happens on notice: NTH cordons the node, adds its own taint (aws-node-termination-handler/spot-itn:NoSchedule) so nothing reschedules onto it, then evicts pods through the Eviction API — which honours PDBs — and finally force-deletes anything still hanging when the grace window closes.

On OpenShift, the DaemonSet needs a ServiceAccount bound to an SCC. The upstream chart runs with hostNetwork: true to reach IMDS; grant the narrowest SCC that works:

oc adm policy add-scc-to-user hostnetwork \
  -z aws-node-termination-handler -n kube-system
Enter fullscreen mode Exit fullscreen mode

Queue processor mode — SQS + EventBridge

In queue mode, EventBridge forwards Spot ITN, rebalance recommendations, ASG lifecycle hooks and EC2 Instance State-change events to an SQS queue; a single Deployment consumes them and drains the matching node. Advantages: it survives the node itself becoming unresponsive, and it handles ASG scale-in and scheduled maintenance uniformly. Cost: an IAM role (use IRSA / OpenShift's cloud-credential-operator, never the node instance profile), an SQS queue, and EventBridge rules.

helm upgrade --install aws-node-termination-handler eks/aws-node-termination-handler \
  --namespace kube-system \
  --set enableSqsTerminationDraining=true \
  --set queueURL=https://sqs.eu-west-1.amazonaws.com/111122223333/nth-queue \
  --set serviceAccount.annotations."eks\.amazonaws\.com/role-arn"=arn:aws:iam::111122223333:role/nth-queue-processor \
  --set checkTagBeforeDraining=true \
  --set managedTag=aws-node-termination-handler/managed
Enter fullscreen mode Exit fullscreen mode

Validate the drain path before production

Do not wait for a real interruption. AWS Fault Injection Simulator can send a genuine spot interruption notice:

INSTANCE_ID=i-0abc123def4567890
cat > /tmp/fis-spot.json <<EOF
{
  "description": "spot ITN drill",
  "roleArn": "arn:aws:iam::111122223333:role/fis-experiment-role",
  "stopConditions": [{"source": "none"}],
  "targets": {
    "oneSpot": {
      "resourceType": "aws:ec2:spot-instance",
      "resourceArns": ["arn:aws:ec2:eu-west-1:111122223333:instance/$INSTANCE_ID"],
      "selectionMode": "ALL"
    }
  },
  "actions": {
    "interrupt": {
      "actionId": "aws:ec2:send-spot-instance-interruptions",
      "parameters": {"durationBeforeInterruption": "PT2M"},
      "targets": {"SpotInstances": "oneSpot"}
    }
  }
}
EOF
aws fis create-experiment-template --cli-input-json file:///tmp/fis-spot.json
Enter fullscreen mode Exit fullscreen mode

Then watch the node and the events:

oc get nodes -l capacity-type=spot -w
oc get events -A --field-selector reason=SpotInterruption --sort-by=.lastTimestamp
Enter fullscreen mode Exit fullscreen mode

A cheap, cloud-agnostic smoke test of the same code path:

oc adm drain ip-10-0-42-17.eu-west-1.compute.internal \
  --ignore-daemonsets --delete-emptydir-data --grace-period=90 --timeout=110s
Enter fullscreen mode Exit fullscreen mode

If that command cannot finish in 110 seconds, neither can a real interruption.

Make batch workloads interruption-native

Node handling buys you a clean eviction. It does not save your computation. That part is application design.

The checkpointing contract

Four rules:

  1. Split work into units small enough that redoing one is cheap — target under 60 seconds of work per unit.
  2. Persist progress to durable, shared storage (S3, an RWX PVC, a database row), never to the node's local disk.
  3. Handle SIGTERM: stop pulling new units, flush the current checkpoint, exit 0 if the unit completed or a non-zero code that signals "resume me".
  4. Be idempotent: a unit can be processed twice. Make writes keyed and overwrite-safe.

A minimal Python worker skeleton:

import json, os, signal, sys
import boto3

STOP = False
def on_sigterm(signum, frame):
    global STOP
    STOP = True
signal.signal(signal.SIGTERM, on_sigterm)

s3 = boto3.client("s3")
BUCKET, JOB_ID = os.environ["CKPT_BUCKET"], os.environ["JOB_ID"]
KEY = f"checkpoints/{JOB_ID}/{os.environ['JOB_COMPLETION_INDEX']}.json"

def load():
    try:
        return json.loads(s3.get_object(Bucket=BUCKET, Key=KEY)["Body"].read())
    except s3.exceptions.NoSuchKey:
        return {"offset": 0}

def save(state):
    s3.put_object(Bucket=BUCKET, Key=KEY, Body=json.dumps(state).encode(),
                  ServerSideEncryption="aws:kms")

state = load()
print(f"resuming at offset {state['offset']}", flush=True)

for offset in range(state["offset"], TOTAL_UNITS):
    process_unit(offset)              # must be idempotent
    state["offset"] = offset + 1
    if offset % 50 == 0 or STOP:
        save(state)
    if STOP:
        print("SIGTERM received, checkpoint flushed", flush=True)
        sys.exit(75)                  # EX_TEMPFAIL -> retry
save(state)
Enter fullscreen mode Exit fullscreen mode

The Job manifest

podFailurePolicy is the key piece: a pod killed by a disruption gets the DisruptionTarget condition, and you do not want those retries counting against backoffLimit.

apiVersion: batch/v1
kind: Job
metadata:
  name: nightly-reindex
  namespace: batch
spec:
  completions: 120
  parallelism: 20
  completionMode: Indexed
  backoffLimit: 6
  podFailurePolicy:
    rules:
      - action: Ignore                      # disruption != application failure
        onPodConditions:
          - type: DisruptionTarget
      - action: FailJob                     # unrecoverable config error
        onExitCodes:
          containerName: worker
          operator: In
          values: [78]
  template:
    spec:
      restartPolicy: Never
      terminationGracePeriodSeconds: 60
      nodeSelector:
        capacity-type: spot
      tolerations:
        - key: capacity-type
          operator: Equal
          value: spot
          effect: NoSchedule
      serviceAccountName: reindex-worker
      containers:
        - name: worker
          image: quay.io/acme/reindex:2.4.0
          env:
            - name: JOB_ID
              value: nightly-reindex
            - name: CKPT_BUCKET
              value: acme-batch-checkpoints
            - name: JOB_COMPLETION_INDEX
              valueFrom:
                fieldRef:
                  fieldPath: metadata.annotations['batch.kubernetes.io/job-completion-index']
          resources:
            requests: {cpu: "1", memory: 2Gi}
            limits: {memory: 2Gi}
Enter fullscreen mode Exit fullscreen mode

For long pipelines, consider a two-tier pool: run the job on spot, but keep a small on-demand MachineSet (capacity-type: on-demand) as a fallback. A simple pattern is a second Job, selecting on-demand nodes, triggered by your scheduler only after N spot attempts.

Measure the real failure rate

Opinions about spot reliability are worthless; counters are not. Three numbers to track:

  1. Interruptions per node-hour on spot, broken down by instance type and AZ.
  2. Drain success ratio: evictions completed before the deadline vs. force-deleted pods.
  3. Batch impact: extra wall-clock time and re-processed units caused by interruptions.

NTH with enablePrometheusServer=true exposes an actions_total counter labelled by event type and outcome. Combine it with kube_node_info from kube-state-metrics:

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: spot-interruptions
  namespace: kube-system
spec:
  groups:
    - name: spot.rules
      interval: 60s
      rules:
        - record: spot:interruptions:rate1h
          expr: sum(rate(actions_total{event_type="SPOT_ITN"}[1h]))
        - record: spot:nodes:count
          expr: count(kube_node_labels{label_capacity_type="spot"})
        - record: spot:interruptions_per_node_hour
          expr: spot:interruptions:rate1h * 3600 / clamp_min(spot:nodes:count, 1)
        - alert: SpotInterruptionRateHigh
          expr: spot:interruptions_per_node_hour > 0.2
          for: 30m
          labels: {severity: warning}
          annotations:
            summary: "More than 1 interruption per 5 node-hours on the spot pool"
            description: "Rebalance instance types/AZs or shift critical batch to on-demand."
        - alert: BatchJobExcessiveRetries
          expr: kube_job_status_failed{namespace="batch"} > 3
          for: 10m
          labels: {severity: warning}
Enter fullscreen mode Exit fullscreen mode

Query the ground truth for a quick sanity check:

# pods killed by disruption in the last hour
oc get events -A --field-selector reason=Evicted --sort-by=.lastTimestamp | tail -20

# how many spot nodes are currently cordoned by NTH
oc get nodes -l capacity-type=spot \
  -o jsonpath='{range .items[?(@.spec.unschedulable==true)]}{.metadata.name}{"\n"}{end}'
Enter fullscreen mode Exit fullscreen mode

Rule of thumb from production fleets: with 3+ instance types across 3 AZs, 0.05–0.15 interruptions per node-hour is normal. Above 0.3 sustained, your instance type selection is fighting the market — diversify or move the workload.

Security best practices

Spot adds churn, and churn amplifies weak IAM and weak node bootstrap hygiene.

  • Lock down IMDS. Require IMDSv2 and set the hop limit to 1 so containers on the pod network cannot reach 169.254.169.254 and steal the node role credentials:
  aws ec2 modify-instance-metadata-options \
    --instance-id i-0abc123def4567890 \
    --http-tokens required --http-put-response-hop-limit 1
Enter fullscreen mode Exit fullscreen mode

Set the same in the MachineSet providerSpec.value.metadataServiceOptions.authentication: Required. If NTH runs in IMDS mode with hostNetwork: true, it still reaches IMDS at hop 1 — that is exactly why the DaemonSet is host-networked and your application pods are not.

  • Defense in depth with NetworkPolicy. Where your CNI enforces it (OVN-Kubernetes does for link-local via egress rules), deny metadata access from application namespaces:
  apiVersion: networking.k8s.io/v1
  kind: NetworkPolicy
  metadata:
    name: deny-imds-egress
    namespace: batch
  spec:
    podSelector: {}
    policyTypes: [Egress]
    egress:
      - to:
          - ipBlock:
              cidr: 0.0.0.0/0
              except: [169.254.169.254/32]
Enter fullscreen mode Exit fullscreen mode
  • Use workload identity, never the node role. The batch worker's S3 checkpoint access must come from IRSA (EKS) or the Cloud Credential Operator (OpenShift), scoped to s3:GetObject/s3:PutObject on arn:aws:s3:::acme-batch-checkpoints/checkpoints/* only.
  • Encrypt checkpoints and treat them as data at rest. SSE-KMS with a customer-managed key, bucket policy denying unencrypted puts, and a lifecycle rule expiring checkpoints after a few days. Never serialize credentials or PII into a checkpoint blob.
  • Scope NTH's RBAC. It legitimately needs get/list/watch/patch on nodes, create on pods/eviction, and list/get on pods and DaemonSets — nothing more. Audit the chart's ClusterRole before installing: helm template ... | oc get -f - -o yaml and review.
  • Constrain the SQS queue. In queue mode, the queue policy should allow events.amazonaws.com and the ASG service principal to sqs:SendMessage and nothing else; the processor role gets sqs:ReceiveMessage, sqs:DeleteMessage, sqs:GetQueueAttributes and autoscaling:CompleteLifecycleAction.
  • Pin and verify images. Nodes recycle constantly, so every reclaim is a fresh image pull. Use digests, a pull-through cache you control, and signature verification (Sigstore policy controller / ClusterImagePolicy).

Key takeaways

Spot is not a reliability downgrade; it is a scheduling contract you must honour explicitly.

  • Isolate capacity: dedicated MachineSets per instance type and AZ, capacity-type=spot label plus a NoSchedule taint, and opt-in via nodeSelector + tolerations. No workload runs on spot by accident.
  • Wire a handler: aws-node-termination-handler in IMDS mode for simplicity, queue mode for ASG and maintenance coverage. Set podTerminationGracePeriod to ~90s so eviction fits inside the 120-second budget.
  • Use PDBs deliberately: maxUnavailable percentages for stateless fleets; an unsatisfiable PDB turns a graceful drain into a hard kill.
  • Make batch resumable: idempotent units, durable checkpoints, a real SIGTERM handler, and podFailurePolicy with action: Ignore on the DisruptionTarget condition so disruptions do not burn your backoffLimit.
  • Drill it: AWS FIS spot interruption experiments, or at minimum oc adm drain --timeout=110s, before you trust the pipeline.
  • Measure it: interruptions per node-hour, drain success ratio, batch re-processing overhead. Those three metrics tell you when to diversify instance types or shift a workload back to on-demand.

Get these right and spot stops being a gamble. It becomes what it should be: the default capacity tier for everything that can be retried, with on-demand reserved for the small fraction of your workloads that genuinely cannot.

Top comments (0)