# Use spot instances

Run interruptible instances in spare room on {{product}}'s own hosts at 60 % below the on-demand price, and handle the two-minute notice.

A spot instance runs in room on Deutsche Cloud's own hosts that nobody pays full price for, at 60 %
below the on-demand price of the same size. When a full-price machine needs that room, the spot
instance gets two minutes' notice and is then stopped or terminated. Use spot for work that can be
stopped and picked up again: CI jobs, batch processing, rendering, test environments, workers that
read from a queue.

| On-demand                                       | Spot                                                                              |
| ----------------------------------------------- | --------------------------------------------------------------------------------- |
| Runs until you stop it                          | Can be interrupted with two minutes' notice                                       |
| On our own hosts or on rented cloud capacity    | Only on our own hosts, never on rented cloud capacity                             |
| Waits for room, or goes to the cloud            | With no spare room, the launch is refused at once                                 |
| Any network, zone, security groups, OS patching | No VPC, subnet, zone, security groups or OS patching on the launch                |
| The size's price                                | 40 % of the size's price per started hour; nothing while an interruption stops it |

The 60 % discount is the price list's for spot today and can change; the instance's bill shows each
spot hour at 0.4 of an hour of its size.

## Prerequisites

- Permission for `ec2:RunInstances`. Starting an interrupted instance yourself needs
  `ec2:StartInstances` on it.
- A size class, or an instance type. A type is bought as its nearest size class, for example
  `performance-2` as `s-2`.

## Launch a spot instance

**Console**
1. Open **Compute**, then choose **Create instance**.
2. Fill in the form (see [Launch an instance](launch-an-instance.md)).
3. Under **Size**, set **Purchasing option** to **Spot · 60 % off**.
4. Under **When interrupted**, choose **Stop** (the default) or **Terminate**.
5. Choose **Create instance**.

The cost box shows the spot price. The network, zone, security group and patching choices on the
form are not sent for a spot instance.

**CLI**
```sh
dcloud ec2 instances run --region-id de1 --size-class s-2 \
  --image-id 114690387 --market-type spot --spot-interruption-behavior stop
```

**API**
```http
POST /ec2/api/instances
{ "sizeClass": "s-2", "imageId": 114690387, "regionId": "de1",
  "marketType": "spot", "spotInterruptionBehavior": "stop" }
```

The answer is `201` with the instance, `marketType` `spot`. With no spare room for the class on
any of our hosts, the answer is `409` with `InsufficientSpotCapacity: no spare room on our hosts
for a s-2 spot instance now (…)`. Nothing is made or billed. Try again later, a smaller class, or
on-demand.

## What happens when it is interrupted

1. A full-price machine needs the room on its host. The spot instance gets two minutes' notice:
   - its event log says when and what;
   - the event bus carries `Spot Instance Interruption Warning` (source `ews.ec2`, detail
     `instance-id`, `instance-action`, `action-time`), which a rule can send to a queue, a webhook
     or a function;
   - `GET /ec2/api/instances/{id}` answers `spotInterruption` with `action`, `noticeAt` and `time`;
   - on the machine, `ews-instance spot` prints `{"action":"stop","time":"…"}` (both `null` while
     nothing is pending).
2. At `time` it is stopped or terminated:
   - **Stop**: the disk stays on the host. Its vCPU and memory go to the full-price machine. When
     the host has room again, Deutsche Cloud starts it again by itself, usually within a few minutes
     of the room coming back. Nothing is billed while it is stopped.
   - **Terminate**: the instance and its disk are deleted.

Only as many spot instances as the full-price machine needs are interrupted, newest first, and only
on the host it lands on.

## Watch for the notice on the machine

A loop that drains work when the notice comes, as a systemd service or in your own program:

```sh
#!/bin/sh
# Polls every 5 seconds; the notice is two minutes.
while sleep 5; do
  action=$(ews-instance spot | sed -n 's/.*"action":"\([a-z]*\)".*/\1/p')
  if [ -n "$action" ]; then
    systemctl stop my-worker   # finish or hand back the current job
    break
  fi
done
```

## Start an interrupted instance yourself

A stopped spot instance starts like any other (**Start** in the console,
`dcloud ec2 instances start <id>`). If its host has no spare room for it, the answer is
`409` `InsufficientSpotCapacity: its host has no spare room for it now`; an instance an
interruption stopped then starts by itself once there is room.

## Limits

- Spot runs on our own hosts only. It is not offered for macOS or Windows Server instances.
- A spot instance cannot be launched into a VPC, a subnet or a zone you name, with security groups,
  or with **Keep OS patched**: those belong to rented cloud capacity. It gets a public address.
- There is no price history and no bidding: the spot price is a fixed share of the size's price.
