Creating and Starting a Preemptible Instance

This page explains how to create and use a preemptible virtual machine (VM) instance. A preemptible instance is an instance you can create and run at a much lower price than normal instances. However, Compute Engine might terminate (preempt) these instances if it requires access to those resources for other tasks. Preemptible instances will always terminate after 24 hours. To learn more about preemptible instances, read the preemptible instances documentation.

Preemptible instances are recommended only for fault-tolerant applications that can withstand instance preemptions. Make sure your application can handle preemptions before you decide to create a preemptible instance. To understand the risks and value of preemptible instances, read the preemptible instances documentation.

Contents

Before you begin

Creating a preemptible instance

Create a preemptible instance through the Google Cloud Platform Console, the gcloud tool, or the API.

Console


Creating a preemptible instance is the same as creating a normal instance, but you enable the preemptible property.

  1. In the Cloud Platform Console, go to the VM Instances page.

    Go to the VM Instances page

  2. Click the Create instance button.
  3. On the Create a new instance page, fill in the desired properties for your instance.
  4. Click Management, disk, networking, SSH keys.
  5. In the Availability policies settings section, set the Preemptibility option to On. This setting disables automatic restart for the instance, and sets the host maintenance action to Terminate.
  6. Click the Create button to create the instance.

gcloud


With gcloud compute, use the same instances create command that you would use to create a normal instance, but add the --preemptible flag.

gcloud compute instances create [INSTANCE_NAME] --preemptible

where [INSTANCE_NAME] is the name of the instance.

API


In the API, construct a normal request to create an instance, but include the preemptible property under scheduling and set it to true. For example:

POST https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/[ZONE]/instances

{
  'machineType': 'zones/[ZONE]/machineTypes/[MACHINE_TYPE]',
  'name': '[INSTANCE_NAME]',
  'scheduling':
  {
    'preemptible': true
  },
  ...
}

Preemptible CPU quotas

Preemptible instances require available CPU quotas like regular instances. To avoid preemptible instances consuming the CPU quotas for your regular instances, you can request a special "Preemptible CPU" quota. After Compute Engine grants you preemptible CPU quota in that region, all preemptible instances will count against that quota. All regular instances will continue to count against the regular CPU quota.

In regions where you don’t have preemptible CPU quota, you can use regular CPU quota to launch preemptible instances. You will also need sufficient IP and disk quota, as usual. Preemptible CPU quota is not visible in the gcloud tool or Cloud Platform Console quota pages unless Compute Engine has granted the quota.

For more information about quotas, visit the Resource Quotas page.

Handling preemption with a shutdown script

When your instance is preempted, you can use a shutdown script to perform cleanup actions before the instance stops. For example, you can gracefully terminate a running process and copy a checkpoint file to Google Cloud Storage.

The following is a shutdown script that you can add to a running preemptible instance or add to a new preemptible instance when you create it. This script runs when the instance starts to shut down, before the operating system's normal kill command terminates all remaining processes. After gracefully terminating the desired program, the script performs a parallel upload of a checkpoint file to a Google Cloud Storage bucket.

#!/bin/bash

MY_PROGRAM="[PROGRAM_NAME]" # For example, "apache2" or "nginx"
MY_USER="[LOCAL_USERNAME]"
CHECKPOINT="/home/$MY_USER/checkpoint.out"
GSUTIL_OPTS="-m -o GSUtil:parallel_composite_upload_threshold=32M"
BUCKET_NAME="[BUCKET_NAME]" # For example, "my-checkpoint-files" (without gs://)

echo "Shutting down!  Seeing if ${MY_PROGRAM} is running."

# Find the newest copy of $MY_PROGRAM
PID="$(pgrep -n "$MY_PROGRAM")"

if [[ "$?" -ne 0 ]]; then
  echo "${MY_PROGRAM} not running, shutting down immediately."
  exit 0
fi

echo "Sending SIGINT to $PID"
kill -2 "$PID"

# Portable waitpid equivalent
while kill -0 "$PID"; do
   sleep 1
done

echo "$PID is done, copying ${CHECKPOINT} to gs://${BUCKET_NAME} as ${MY_USER}"

su "${MY_USER}" -c "gsutil $GSUTIL_OPTS cp $CHECKPOINT gs://${BUCKET_NAME}/"

echo "Done uploading, shutting down."

To add this script to an instance, configure the script to work with an application on your instance and add it to your instance metadata.

  1. Copy or download the shutdown script to your local workstation.
  2. Open the file for edit and change the following variables:
    • [PROGRAM_NAME] is the name of the process or program you want to shut down. For example, apache2 or nginx.
    • [LOCAL_USER] is the username you are logged into the virtual machine as.
    • [BUCKET_NAME] is the name of the Google Cloud Storage bucket where you want to save the program's checkpoint file. Note the bucket name does not start with gs:// in this case.
  3. Save your changes.
  4. Add the shutdown script to a new instance or an existing instance.

This script assumes:

  • The instance was created with at least read-write access to Google Cloud Storage. See the authentication documentation for instructions on how to create an instance with the appropriate scopes.

  • You have an existing Google Cloud Storage bucket and permission to write to it.

Checking if an instance is preemptible

You can check if an instance is configured to be preemptible using the Cloud Platform Console, the gcloud tool, or the API.

Console


Check if an instance is preemptible by viewing the instance properties.

  1. Go to the VM instances page.

    Go to the VM Instances page

  2. Select your project and click Continue.
  3. Click the name of the instance that you want to check. This opens the instance details page.
  4. The preemptible status is specified in the Availability policies section of the instance details.

gcloud


In gcloud compute, use instances describe to get information about an instance, including whether the instance is preemptible.

gcloud compute instances describe [INSTANCE_NAME]

where [INSTANCE_NAME] is the name of the instance.

The response information includes the preemptible status in the scheduling section.

...
scheduling:
  automaticRestart: false
  onHostMaintenance: TERMINATE
  preemptible: true
...

API


To check if an instance is preemptible, use the API to send a GET request to the URI of the instance.

GET https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/[ZONE]/instances/[INSTANCE_NAME]

The response information includes the preemptible status under scheduling.

{
    "kind": "compute#instance",
    "id": "4468501694759003918",
    "creationTimestamp": "2015-04-15T15:40:59.004-07:00",
    "zone": "https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/us-central1-f",
    "status": "RUNNING",
    "name": "example-instance",
    "scheduling":
    {
       "preemptible": true
    },
    ...
 }

Alternatively, you can determine if an instance is preemptible from inside the instance itself. Simply check the metadata server for the scheduling/preemptible value in your instance's default instance metadata.

For example, use curl from within your instance to obtain the value for scheduling/preemptible:

curl "http://metadata.google.internal/computeMetadata/v1/instance/scheduling/preemptible" -H "Metadata-Flavor: Google"
TRUE

If this value is TRUE, the instance is preemptible.

Detecting if an instance was preempted

Determine if an instance was preempted with the Google Cloud Platform Console, the gcloud tool, or the API.

Console


You can check if an instance was preempted by checking the system activity logs.

  1. Go to the Logs page.

    Go to the Logs page

  2. Select your project and click Continue.
  3. Add compute.instances.preempted to the filter by label or text search field. Optionally, you can also enter an instance name if you want to see preemption operations for a specific instance.
  4. Press enter to apply the specified filters. The Cloud Platform Console updates the list of logs to show only the operations where an instance was preempted.
  5. Select an operation in the list to see details about the instance that was preempted.

gcloud


In gcloud compute, use the operations list command to get a list of recent system operations.

gcloud compute operations list

gcloud returns a response similar to:

NAME                  TYPE                         TARGET                                   HTTP_STATUS STATUS TIMESTAMP
systemevent-xxxxxxxx  compute.instances.preempted  us-central1-f/instances/example-instance 200         DONE   2015-04-02T12:12:10.881-07:00

An operation type of compute.instances.preempted indicates that the instance was preempted. You can use the operations describe command to get more information about a specific preemption operation.

gcloud compute operations describe \
    systemevent-xxxxxxxx

gcloud returns a response similar to:

...
operationType: compute.instances.preempted
progress: 100
selfLink: https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/us-central1-f/operations/systemevent-xxxxxxxx
startTime: '2015-04-02T12:12:10.881-07:00'
status: DONE
statusMessage: Instance was preempted.
...

API


To get a list of recent system operations, send a GET request to the URI of global operations.

GET https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/global/operations

The response contains a list of recent operations. If an instance was preempted, the operation includes an operation type of compute.instances.preempted and a status message indicating that the instance was preempted.

{
  "kind": "compute#operation",
  "id": "15041793718812375371",
  "name": "systemevent-xxxxxxxx",
  "zone": "https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/us-central1-f",
  "operationType": "compute.instances.preempted",
  "targetLink": "https://www.googleapis.com/compute/v1/projects/[PROJECT_ID]/zones/us-central1-f/instances/example-instance",
  "targetId": "12820389800990687210",
  "status": "DONE",
  "statusMessage": "Instance was preempted.",
  ...
}

Best practices

Here are some best practices to help you get the most out of preemptible VM instances.

Run large preemptible VM clusters during off peak times

Resources for preemptible VM instances come out of excess and backup Google Cloud Platform Capacity. The load on Google Cloud Platform data centers varies with location and time of day, but generally lowest on nights and weekends. As such, nights and weekends are the best times to run large preemptible VM clusters.

Design your applications to be fault and preemption tolerant

It's important to be prepared for the fact that there will be changes in preemption patterns at different points in time. For example, it is possible that if a zone suffers a partial outage, large numbers of preemptible instances could be preempted in order to make room for regular instances that need to be moved as part of the recovery. In that small window of time, the preemption rate would look very different than on any other day. If your application assumes that preemptions will always be done in small groups, you might not be prepared for such an event. You can test your application's behavior under a preemption event by stopping the VM instance.

Retry creating instances that have been preempted

If you've been preempted, it's a good idea to retry preemptible instances once or twice before falling back to regular instances. Depending on your requirements, it might be a good idea to combine regular and preemptible instances in your clusters to ensure that work proceeds at an adequate pace.

Use shutdown scripts

Manage shutdown and preemption notices with a shutdown script that can save a job's progress so that it can pick up where it left off, rather than start over from scratch.

What's next?

Send feedback about...

Compute Engine Documentation