Creating and managing instances

This page describes how to create, list, edit, and delete Cloud Spanner instances.

Creating an instance

You can create an instance with the gcloud command-line tool or with the Google Cloud Console.

Console

  1. Go to the Create an instance page in the Cloud Console.

    Create an instance

  2. Enter the following values:

    • An instance name to display in the Cloud Console. The instance name must be unique within your Google Cloud project.
    • An instance ID to permanently identify your instance. The instance ID must also be unique within your Google Cloud project. You cannot change the instance ID later.
    • A configuration, which defines the geographic location of the instance's nodes and affects how data is replicated. Learn more about instance configurations.
    • The number of nodes for the instance. The number of nodes determines the amount of serving and storage resources that are available to databases in the instance.
  3. Click Create to create the instance.

The following screenshot shows the instance creation page:

Screenshot of the instance creation page

gcloud

Use the gcloud spanner instances create command:

gcloud spanner instances create [INSTANCE-ID] --config=[INSTANCE-CONFIG] \
    --description="[INSTANCE-NAME]" --nodes=[NODE-COUNT]

Provide the following values:

  • [INSTANCE-ID]: A permanent identifier that is unique within your Google Cloud project. You cannot change the instance ID later.
  • [INSTANCE-CONFIG]: The instance configuration, which defines the geographic location of the instance's nodes and affects how data is replicated. Learn more about instance configurations.
  • [INSTANCE-NAME]: The name to display for the instance in the Cloud Console. The instance name must be unique within your Google Cloud project.
  • [NODE-COUNT]: The number of nodes for the instance. The number of nodes determines the amount of serving and storage resources that are available to databases in the instance.

For example:

gcloud spanner instances create test-instance --config=regional-us-central1 \
    --description="Test Instance" --nodes=1

You should see a message similar to the following example:

Creating instance...done.

C++

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

void CreateInstance(google::cloud::spanner::InstanceAdminClient client,
                    std::string const& project_id,
                    std::string const& instance_id,
                    std::string const& display_name,
                    std::string const& config) {
  namespace spanner = google::cloud::spanner;
  spanner::Instance in(project_id, instance_id);

  std::string instance_config =
      "projects/" + project_id + "/instanceConfigs/" + config;
  auto instance =
      client
          .CreateInstance(
              spanner::CreateInstanceRequestBuilder(in, instance_config)
                  .SetDisplayName(display_name)
                  .SetNodeCount(1)
                  .SetLabels({{"cloud_spanner_samples", "true"}})
                  .Build())
          .get();
  if (!instance) throw std::runtime_error(instance.status().message());
  std::cout << "Created instance [" << in << "]\n";
}

Go

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

import (
	"context"
	"fmt"
	"io"

	instance "cloud.google.com/go/spanner/admin/instance/apiv1"
	instancepb "google.golang.org/genproto/googleapis/spanner/admin/instance/v1"
)

func createInstance(ctx context.Context, w io.Writer, projectID, instanceID string) error {
	instanceAdmin, err := instance.NewInstanceAdminClient(ctx)
	if err != nil {
		return err
	}
	defer instanceAdmin.Close()

	op, err := instanceAdmin.CreateInstance(ctx, &instancepb.CreateInstanceRequest{
		Parent:     fmt.Sprintf("projects/%s", projectID),
		InstanceId: instanceID,
		Instance: &instancepb.Instance{
			Config:      fmt.Sprintf("projects/%s/instanceConfigs/%s", projectID, "regional-us-central1"),
			DisplayName: instanceID,
			NodeCount:   1,
			Labels:      map[string]string{"cloud_spanner_samples": "true"},
		},
	})
	if err != nil {
		return fmt.Errorf("could not create instance %s: %v", fmt.Sprintf("projects/%s/instances/%s", projectID, instanceID), err)
	}
	// Wait for the instance creation to finish.
	i, err := op.Wait(ctx)
	if err != nil {
		return fmt.Errorf("waiting for instance creation to finish failed: %v", err)
	}
	// The instance may not be ready to serve yet.
	if i.State != instancepb.Instance_READY {
		fmt.Fprintf(w, "instance state is not READY yet. Got state %v\n", i.State)
	}
	fmt.Fprintf(w, "Created instance [%s]\n", instanceID)
	return nil
}

Java

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.spanner.Instance;
import com.google.cloud.spanner.InstanceAdminClient;
import com.google.cloud.spanner.InstanceConfigId;
import com.google.cloud.spanner.InstanceId;
import com.google.cloud.spanner.InstanceInfo;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import com.google.spanner.admin.instance.v1.CreateInstanceMetadata;
import java.util.concurrent.ExecutionException;

class CreateInstanceExample {

  static void createInstance() {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "my-project";
    String instanceId = "my-instance";
    createInstance(projectId, instanceId);
  }

  static void createInstance(String projectId, String instanceId) {
    Spanner spanner = SpannerOptions.newBuilder().setProjectId(projectId).build().getService();
    InstanceAdminClient instanceAdminClient = spanner.getInstanceAdminClient();

    // Set Instance configuration.
    String configId = "regional-us-central1";
    int nodeCount = 2;
    String displayName = "Descriptive name";

    // Create an InstanceInfo object that will be used to create the instance.
    InstanceInfo instanceInfo =
        InstanceInfo.newBuilder(InstanceId.of(projectId, instanceId))
            .setInstanceConfigId(InstanceConfigId.of(projectId, configId))
            .setNodeCount(nodeCount)
            .setDisplayName(displayName)
            .build();
    OperationFuture<Instance, CreateInstanceMetadata> operation =
        instanceAdminClient.createInstance(instanceInfo);
    try {
      // Wait for the createInstance operation to finish.
      Instance instance = operation.get();
      System.out.printf("Instance %s was successfully created%n", instance.getId());
    } catch (ExecutionException e) {
      System.out.printf(
          "Error: Creating instance %s failed with error message %s%n",
          instanceInfo.getId(), e.getMessage());
    } catch (InterruptedException e) {
      System.out.println("Error: Waiting for createInstance operation to finish was interrupted");
    } finally {
      spanner.close();
    }
  }
}

Node.js

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

// Imports the Google Cloud client library
const {Spanner} = require('@google-cloud/spanner');

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const projectId = 'my-project-id';
// const instanceId = 'my-instance';

// Creates a client
const spanner = new Spanner({
  projectId: projectId,
});

const instance = spanner.instance(instanceId);

// Creates a new instance
try {
  console.log(`Creating instance ${instance.formattedName_}.`);
  const [, operation] = await instance.create({
    config: 'regional-us-central1',
    nodes: 1,
    displayName: 'This is a display name.',
    labels: {
      ['cloud_spanner_samples']: 'true',
      created: Math.round(Date.now() / 1000).toString(), // current time
    },
  });

  console.log(`Waiting for operation on ${instance.id} to complete...`);
  await operation.promise();

  console.log(`Created instance ${instanceId}.`);
} catch (err) {
  console.error('ERROR:', err);
}

PHP

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

use Google\Cloud\Spanner\SpannerClient;

/**
 * Creates an instance.
 * Example:
 * ```
 * create_instance($instanceId);
 * ```
 *
 * @param string $instanceId The Spanner instance ID.
 */
function create_instance($instanceId)
{
    $spanner = new SpannerClient();
    $instanceConfig = $spanner->instanceConfiguration(
        'regional-us-central1'
    );
    $operation = $spanner->createInstance(
        $instanceConfig,
        $instanceId,
        [
            'displayName' => 'This is a display name.',
            'nodeCount' => 1,
            'labels' => [
                'cloud_spanner_samples' => true,
            ]
        ]
    );

    print('Waiting for operation to complete...' . PHP_EOL);
    $operation->pollUntilComplete();

    printf('Created instance %s' . PHP_EOL, $instanceId);
}

Python

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

def create_instance(instance_id):
    """Creates an instance."""
    spanner_client = spanner.Client()

    config_name = "{}/instanceConfigs/regional-us-central1".format(
        spanner_client.project_name
    )

    instance = spanner_client.instance(
        instance_id,
        configuration_name=config_name,
        display_name="This is a display name.",
        node_count=1,
    )

    operation = instance.create()

    print("Waiting for operation to complete...")
    operation.result(120)

    print("Created instance {}".format(instance_id))

Ruby

To learn how to install and use the client library for Cloud Spanner, see the Cloud Spanner Client Libraries.

# project_id  = "Your Google Cloud project ID"
# instance_id = "Your Spanner instance ID"

require "google/cloud/spanner"

spanner  = Google::Cloud::Spanner.new project: project_id
instance = spanner.instance instance_id

job = spanner.create_instance instance_id,
                              name:   instance_id,
                              config: "regional-us-central1",
                              nodes:  2,
                              labels: { cloud_spanner_samples: true }

puts "Waiting for create instance operation to complete"

job.wait_until_done!

if job.error?
  puts job.error
else
  puts "Created instance #{instance_id}"
end

Listing instances

Console

Go to the Spanner Instances page in the Cloud Console.

Go to the Instances page

The Cloud Console shows a list of your Cloud Spanner instances, along with each instance's ID, display name, configuration, and number of nodes.

gcloud

Use the gcloud spanner instances list command:

gcloud spanner instances list

The gcloud tool prints a list of your Cloud Spanner instances, along with each instance's ID, display name, configuration, and number of nodes.

Editing an instance

The following sections explain how to change an instance's display name and number of nodes. You cannot change the instance ID or instance configuration.

Changing the display name

Console

  1. Go to the Spanner Instances page in the Cloud Console.

    Go to the Instances page

  2. Click the name of the instance that you want to rename.

  3. Click Edit instance.

  4. Enter a new instance name. This name must be unique within the Google Cloud project.

  5. Click Save.

gcloud

Use the gcloud spanner instances update command:

gcloud spanner instances update [INSTANCE-ID] --description=[INSTANCE-NAME]

Provide the following values:

  • [INSTANCE-ID]: The permanent identifier for the instance.
  • [INSTANCE-NAME]: The name to display for the instance in the Cloud Console. The instance name must be unique within your Google Cloud project.

Changing the number of nodes

You must provision enough nodes to keep CPU utilization and storage utilization below the recommended maximums. For more information about the resources provided by a node, see the quotas and limits for Cloud Spanner.

There are a few cases in which you cannot remove nodes from an existing instance:

  • Removing the nodes would require your instance to store more than 2 TB of data per node.
  • Based on your historic usage patterns, Cloud Spanner has created a large number of splits for your instance's data, and Cloud Spanner would not be able to manage the splits after removing the nodes.

When removing nodes, monitor your CPU utilization and request latencies in Cloud Monitoring to ensure CPU utilization stays below 65% for regional instances and 45% for each region in multi-region instances. You may experience a temporary increase in request latencies while removing nodes.

If you want to increase the number of nodes in an instance, your Google Cloud project must have sufficient quota to add the nodes.

Console

  1. Go to the Spanner Instances page in the Cloud Console.

    Go to the Instances page

  2. Click the name of the instance that you want to change.

  3. Click Edit Instance.

  4. Enter the number of nodes that you want.

  5. Click Save.

    If you see a dialog that says you have insufficient quota to add nodes in this location, follow the instructions to request a higher quota.

gcloud

Use the gcloud spanner instances update command:

gcloud spanner instances update [INSTANCE-ID] --nodes=[NODE-COUNT]

Provide the following values:

  • [INSTANCE-ID]: The permanent identifier for the instance.
  • [NODE-COUNT]: The number of nodes for the instance.

Deleting an instance

Console

  1. Go to the Spanner Instances page in the Cloud Console.

    Go to the Instances page

  2. Click the name of the instance that you want to delete.

  3. Click Delete instance.

  4. Follow the instructions to confirm that you want to delete the instance.

  5. Click Delete.

gcloud

Use the gcloud spanner instances delete command, replacing [INSTANCE-ID] with the instance ID:

gcloud spanner instances delete [INSTANCE-ID]

What's next