Create backups Stay organized with collections Save and categorize content based on your preferences.
This page offers information about how you can create backups ofSpanner databases.
For more information about backups, seeBackups overview.You can back up databases using the following ways:
- Using the Google Cloud console.
- Using the Google Cloud CLI.
- Using the client libraries.
- Using theREST orRPC APIs.
Before you begin
To get the permissions that you need to create backups, ask your administrator to grant you the following IAM roles on the instance:
- Create, view, update, and delete backups:Cloud Spanner Backup Admin (
roles/spanner.backupAdmin) - Create and view backups:Cloud Spanner Backup Writer (
roles/spanner.backupWriter)
- Create, view, update, and delete backups:Cloud Spanner Backup Admin (
The gcloud CLI examples on this page make the following assumptions:
- You have already set upgcloud CLI for use withSpanner. If you are new to using gcloud CLI withSpanner, seeCreate and query a database using thegcloud CLI.
You have configured gcloud CLI with your project. For example:
gcloudconfigsetcore/projectPROJECT_ID
Create a backup
When you create a backup, Spanner createsabackup resource and a long-runningbackup operation to trackthe progress of the backup. The newly created backup resides in the sameinstance, region, and project as its source database.
You must specify the following information when creating a backup:
- A source database ID.
- A name for the backup resource.
- An expiration date (up to 1 year from backup creationtime).
Optionally, you can specify aversionTime for the source database,which lets you back up your database to an earlier point in time.TheversionTime field is typically used either to synchronize the backups ofmultiple databases or to recover data usingpoint-in-time recovery (PITR).IfversionTime is not specified, then it is set to thecreateTime of the backup.
You can also create backups on a specified frequency by using a backup schedule.For more information, seeCreate and manage backup schedules.
Console
In the Google Cloud console, go to the SpannerInstances page.
Click the instance that contains the database that you want to back up.
Click the database.
In the navigation pane, clickBackup/Restore.
In theBackups tab, clickCreate backup.
Fill out the form, and clickCreate.
To check the progress of a backup operation, seeCheck the operation progress.
gcloud
Before using any of the command data below, make the following replacements:
- INSTANCE_ID: the Spanner instance ID.
- DATABASE_ID: the Spanner database ID.
- BACKUP_NAME: the Spanner backup name.
- RETENTION_PERIOD: the retention period of the backup created. For example, if you want the retention duration to be one day, you can use
86400s. - ENCRYPTION_TYPE: the encryption type of backup created. Valid values are
USE_CONFIG_DEFAULT_OR_BACKUP_ENCRYPTION,GOOGLE_DEFAULT_ENCRYPTION, orCUSTOMER_MANAGED_ENCRYPTION. If you useCUSTOMER_MANAGED_ENCRYPTION, you must specify akmsKeyName.
Execute the following command:
Linux, macOS, or Cloud Shell
Note: Ensure you have initialized the Google Cloud CLI with authentication and a project by running eithergcloud init; orgcloud auth login andgcloud config set project.gcloudspannerbackupscreateBACKUP_NAME\--instance=INSTANCE_ID\--database=DATABASE_ID\--retention-period=RETENTION_PERIOD\--encryption-type=ENCRYPTION_TYPE\--async
Windows (PowerShell)
Note: Ensure you have initialized the Google Cloud CLI with authentication and a project by running eithergcloud init; orgcloud auth login andgcloud config set project.gcloudspannerbackupscreateBACKUP_NAME`--instance=INSTANCE_ID`--database=DATABASE_ID`--retention-period=RETENTION_PERIOD`--encryption-type=ENCRYPTION_TYPE`--async
Windows (cmd.exe)
Note: Ensure you have initialized the Google Cloud CLI with authentication and a project by running eithergcloud init; orgcloud auth login andgcloud config set project.gcloudspannerbackupscreateBACKUP_NAME^--instance=INSTANCE_ID^--database=DATABASE_ID^--retention-period=RETENTION_PERIOD^--encryption-type=ENCRYPTION_TYPE^--async
You should receive a response similar to the following:
Create request issued for:BACKUP_NAMECheck operation [projects/PROJECT_ID/instances/INSTANCE_ID/backups/BACKUP_NAME/operations/_auto_op_234567] for status.
Here are some usage notes:
- To set the backup's expiration date, specify either the
--retention-periodor--expiration-dateflag. For information on date syntax, seegcloud topic datetimes. - The name of the backup must be unique in the instance.
- The command returns immediately because of the
--asyncflag. Without theflag, the command will wait for the backup operation to complete. - Specify the
--helpflag to get help for any command.
To check the progress of a backup operation, seeCheck the operation progress.
Client libraries
The following code sample creates a backup at a specificversion_timeand then waits for it to complete. Once complete, it verifies that the backup isready and retrieves some information about it, such as its name, size, andcreate time.
C++
voidCreateBackup(google::cloud::spanner_admin::DatabaseAdminClientclient,std::stringconst&project_id,std::stringconst&instance_id,std::stringconst&database_id,std::stringconst&backup_id,google::cloud::spanner::Timestampexpire_time,google::cloud::spanner::Timestampversion_time){google::cloud::spanner::Databasedatabase(project_id,instance_id,database_id);google::spanner::admin::database::v1::CreateBackupRequestrequest;request.set_parent(database.instance().FullName());request.set_backup_id(backup_id);request.mutable_backup()->set_database(database.FullName());*request.mutable_backup()->mutable_expire_time()=expire_time.get<google::protobuf::Timestamp>().value();*request.mutable_backup()->mutable_version_time()=version_time.get<google::protobuf::Timestamp>().value();autobackup=client.CreateBackup(request).get();if(!backup)throwstd::move(backup).status();std::cout <<"Backup " <<backup->name() <<" of " <<backup->database() <<" of size " <<backup->size_bytes() <<" bytes as of " <<google::cloud::spanner::MakeTimestamp(backup->version_time()).value() <<" was created at " <<google::cloud::spanner::MakeTimestamp(backup->create_time()).value() <<".\n";}C#
usingGoogle.Cloud.Spanner.Admin.Database.V1;usingGoogle.Cloud.Spanner.Common.V1;usingGoogle.LongRunning;usingGoogle.Protobuf.WellKnownTypes;usingSystem;publicclassCreateBackupSample{publicBackupCreateBackup(stringprojectId,stringinstanceId,stringdatabaseId,stringbackupId,DateTimeversionTime){// Create the DatabaseAdminClient instance.DatabaseAdminClientdatabaseAdminClient=DatabaseAdminClient.Create();// Initialize request parameters.Backupbackup=newBackup{DatabaseAsDatabaseName=DatabaseName.FromProjectInstanceDatabase(projectId,instanceId,databaseId),ExpireTime=DateTime.UtcNow.AddDays(14).ToTimestamp(),VersionTime=versionTime.ToTimestamp(),};InstanceNameinstanceName=InstanceName.FromProjectInstance(projectId,instanceId);// Make the CreateBackup request.Operation<Backup,CreateBackupMetadata>response=databaseAdminClient.CreateBackup(instanceName,backup,backupId);Console.WriteLine("Waiting for the operation to finish.");// Poll until the returned long-running operation is complete.Operation<Backup,CreateBackupMetadata>completedResponse=response.PollUntilCompleted();if(completedResponse.IsFaulted){Console.WriteLine($"Error while creating backup: {completedResponse.Exception}");throwcompletedResponse.Exception;}Console.WriteLine($"Backup created successfully.");// GetBackup to get more information about the created backup.BackupNamebackupName=BackupName.FromProjectInstanceBackup(projectId,instanceId,backupId);backup=databaseAdminClient.GetBackup(backupName);Console.WriteLine($"Backup {backup.Name} of size {backup.SizeBytes} bytes "+$"was created at {backup.CreateTime} from {backup.Database} "+$"and is in state {backup.State} "+$"and has version time {backup.VersionTime}");returnbackup;}}Go
import("context""fmt""io""regexp""time"database"cloud.google.com/go/spanner/admin/database/apiv1"adminpb"cloud.google.com/go/spanner/admin/database/apiv1/databasepb"pbt"github.com/golang/protobuf/ptypes/timestamp")funccreateBackup(ctxcontext.Context,wio.Writer,db,backupIDstring,versionTimetime.Time)error{// versionTime := time.Now().AddDate(0, 0, -1) // one day agomatches:=regexp.MustCompile("^(.+)/databases/(.+)$").FindStringSubmatch(db)ifmatches==nil||len(matches)!=3{returnfmt.Errorf("createBackup: invalid database id %q",db)}adminClient,err:=database.NewDatabaseAdminClient(ctx)iferr!=nil{returnfmt.Errorf("createBackup.NewDatabaseAdminClient: %w",err)}deferadminClient.Close()expireTime:=time.Now().AddDate(0,0,14)// Create a backup.req:=adminpb.CreateBackupRequest{Parent:matches[1],BackupId:backupID,Backup:&adminpb.Backup{Database:db,ExpireTime:&pbt.Timestamp{Seconds:expireTime.Unix(),Nanos:int32(expireTime.Nanosecond())},VersionTime:&pbt.Timestamp{Seconds:versionTime.Unix(),Nanos:int32(versionTime.Nanosecond())},},}op,err:=adminClient.CreateBackup(ctx,&req)iferr!=nil{returnfmt.Errorf("createBackup.CreateBackup: %w",err)}// Wait for backup operation to complete.backup,err:=op.Wait(ctx)iferr!=nil{returnfmt.Errorf("createBackup.Wait: %w",err)}// Get the name, create time, version time and backup size.backupCreateTime:=time.Unix(backup.CreateTime.Seconds,int64(backup.CreateTime.Nanos))backupVersionTime:=time.Unix(backup.VersionTime.Seconds,int64(backup.VersionTime.Nanos))fmt.Fprintf(w,"Backup %s of size %d bytes was created at %s with version time %s\n",backup.Name,backup.SizeBytes,backupCreateTime.Format(time.RFC3339),backupVersionTime.Format(time.RFC3339))returnnil}Java
staticvoidcreateBackup(DatabaseAdminClientdbAdminClient,StringprojectId,StringinstanceId,StringdatabaseId,StringbackupId,TimestampversionTime){// Set expire time to 14 days from now.TimestampexpireTime=Timestamp.newBuilder().setSeconds(TimeUnit.MILLISECONDS.toSeconds((System.currentTimeMillis()+TimeUnit.DAYS.toMillis(14)))).build();BackupNamebackupName=BackupName.of(projectId,instanceId,backupId);Backupbackup=Backup.newBuilder().setName(backupName.toString()).setDatabase(DatabaseName.of(projectId,instanceId,databaseId).toString()).setExpireTime(expireTime).setVersionTime(versionTime).build();// Initiate the request which returns an OperationFuture.System.out.println("Creating backup ["+backupId+"]...");try{// Wait for the backup operation to complete.backup=dbAdminClient.createBackupAsync(InstanceName.of(projectId,instanceId),backup,backupId).get();System.out.println("Created backup ["+backup.getName()+"]");}catch(ExecutionExceptione){throwSpannerExceptionFactory.asSpannerException(e);}catch(InterruptedExceptione){throwSpannerExceptionFactory.propagateInterrupt(e);}// Reload the metadata of the backup from the server.backup=dbAdminClient.getBackup(backup.getName());System.out.println(String.format("Backup %s of size %d bytes was created at %s for version of database at %s",backup.getName(),backup.getSizeBytes(),java.time.OffsetDateTime.ofInstant(Instant.ofEpochSecond(backup.getCreateTime().getSeconds(),backup.getCreateTime().getNanos()),ZoneId.systemDefault()),java.time.OffsetDateTime.ofInstant(Instant.ofEpochSecond(backup.getVersionTime().getSeconds(),backup.getVersionTime().getNanos()),ZoneId.systemDefault())));}Note: The old client library interface code samples for Java are archived inGitHub.
Node.js
// Imports the Google Cloud client library and precise date libraryconst{Spanner,protos}=require('@google-cloud/spanner');const{PreciseDate}=require('@google-cloud/precise-date');/** * TODO(developer): Uncomment the following lines before running the sample. */// const projectId = 'my-project-id';// const instanceId = 'my-instance';// const databaseId = 'my-database';// const backupId = 'my-backup';// const versionTime = Date.now() - 1000 * 60 * 60 * 24; // One day ago// Creates a clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner Database Admin Client objectconstdatabaseAdminClient=spanner.getDatabaseAdminClient();// Creates a new backup of the databasetry{console.log(`Creating backup of database${databaseAdminClient.databasePath(projectId,instanceId,databaseId,)}.`,);// Expire backup 14 days in the futureconstexpireTime=Date.now()+1000*60*60*24*14;// Create a backup of the state of the database at the current time.const[operation]=awaitdatabaseAdminClient.createBackup({parent:databaseAdminClient.instancePath(projectId,instanceId),backupId:backupId,backup:(protos.google.spanner.admin.database.v1.Backup={database:databaseAdminClient.databasePath(projectId,instanceId,databaseId,),expireTime:Spanner.timestamp(expireTime).toStruct(),versionTime:Spanner.timestamp(versionTime).toStruct(),name:databaseAdminClient.backupPath(projectId,instanceId,backupId),}),});console.log(`Waiting for backup${databaseAdminClient.backupPath(projectId,instanceId,backupId,)} to complete...`,);awaitoperation.promise();// Verify backup is readyconst[backupInfo]=awaitdatabaseAdminClient.getBackup({name:databaseAdminClient.backupPath(projectId,instanceId,backupId),});if(backupInfo.state==='READY'){console.log(`Backup${backupInfo.name} of size `+`${backupInfo.sizeBytes} bytes was created at `+`${newPreciseDate(backupInfo.createTime).toISOString()} `+'for version of database at '+`${newPreciseDate(backupInfo.versionTime).toISOString()}`,);}else{console.error('ERROR: Backup is not ready.');}}catch(err){console.error('ERROR:',err);}finally{// Close the spanner client when finished.// The databaseAdminClient does not require explicit closure. The closure of the Spanner client will automatically close the databaseAdminClient.spanner.close();}Note: The old client library interface code samples for Node.js are archived inGitHub.
PHP
use Google\Cloud\Spanner\Admin\Database\V1\Backup;use Google\Cloud\Spanner\Admin\Database\V1\GetBackupRequest;use Google\Cloud\Spanner\Admin\Database\V1\Client\DatabaseAdminClient;use Google\Cloud\Spanner\Admin\Database\V1\CreateBackupRequest;use Google\Protobuf\Timestamp;/** * Create a backup. * Example: * ``` * create_backup($projectId, $instanceId, $databaseId, $backupId, $versionTime); * ``` * * @param string $projectId The Google Cloud project ID. * @param string $instanceId The Spanner instance ID. * @param string $databaseId The Spanner database ID. * @param string $backupId The Spanner backup ID. * @param string $versionTime The version of the database to backup. Read more * at https://cloud.google.com/spanner/docs/reference/rest/v1/projects.instances.backups#Backup.FIELDS.version_time */function create_backup( string $projectId, string $instanceId, string $databaseId, string $backupId, string $versionTime = '-1hour'): void { $databaseAdminClient = new DatabaseAdminClient(); $databaseFullName = DatabaseAdminClient::databaseName($projectId, $instanceId, $databaseId); $instanceFullName = DatabaseAdminClient::instanceName($projectId, $instanceId); $timestamp = new Timestamp(); $timestamp->setSeconds((new \DateTime($versionTime))->getTimestamp()); $expireTime = new Timestamp(); $expireTime->setSeconds((new \DateTime('+14 days'))->getTimestamp()); $request = new CreateBackupRequest([ 'parent' => $instanceFullName, 'backup_id' => $backupId, 'backup' => new Backup([ 'database' => $databaseFullName, 'expire_time' => $expireTime, 'version_time' => $timestamp ]) ]); $operation = $databaseAdminClient->createBackup($request); print('Waiting for operation to complete...' . PHP_EOL); $operation->pollUntilComplete(); $request = new GetBackupRequest(); $request->setName($databaseAdminClient->backupName($projectId, $instanceId, $backupId)); $info = $databaseAdminClient->getBackup($request); printf( 'Backup %s of size %d bytes was created at %d for version of database at %d' . PHP_EOL, basename($info->getName()), $info->getSizeBytes(), $info->getCreateTime()->getSeconds(), $info->getVersionTime()->getSeconds());}Note: The old client library interface code samples for PHP are archived inGitHub.
Python
defcreate_backup(instance_id,database_id,backup_id,version_time):"""Creates a backup for a database."""fromgoogle.cloud.spanner_admin_database_v1.typesimportbackupasbackup_pbspanner_client=spanner.Client()database_admin_api=spanner_client.database_admin_api# Create a backupexpire_time=datetime.utcnow()+timedelta(days=14)request=backup_pb.CreateBackupRequest(parent=database_admin_api.instance_path(spanner_client.project,instance_id),backup_id=backup_id,backup=backup_pb.Backup(database=database_admin_api.database_path(spanner_client.project,instance_id,database_id),expire_time=expire_time,version_time=version_time,),)operation=database_admin_api.create_backup(request)# Wait for backup operation to complete.backup=operation.result(2100)# Verify that the backup is ready.assertbackup.state==backup_pb.Backup.State.READYprint("Backup{} of size{} bytes was created at{} for version of database at{}".format(backup.name,backup.size_bytes,backup.create_time,backup.version_time))Note: The old client library interface code samples for Python are archived inGitHub.
Ruby
# project_id = "Your Google Cloud project ID"# instance_id = "Your Spanner instance ID"# database_id = "Your Spanner database ID"# backup_id = "Your Spanner backup ID"# version_time = Time.now - 60 * 60 * 24 # 1 day agorequire"google/cloud/spanner"require"google/cloud/spanner/admin/database"database_admin_client=Google::Cloud::Spanner::Admin::Database.database_admininstance_path=database_admin_client.instance_pathproject:project_id,instance:instance_iddb_path=database_admin_client.database_pathproject:project_id,instance:instance_id,database:database_idbackup_path=database_admin_client.backup_pathproject:project_id,instance:instance_id,backup:backup_idexpire_time=Time.now+(14*24*3600)# 14 days from nowjob=database_admin_client.create_backupparent:instance_path,backup_id:backup_id,backup:{database:db_path,expire_time:expire_time,version_time:version_time}puts"Backup operation in progress"job.wait_until_done!backup=database_admin_client.get_backupname:backup_pathputs"Backup#{backup_id} of size#{backup.size_bytes} bytes was created at#{backup.create_time} for version of database at#{backup.version_time}"What's next
To learn more about backups, seeBackups overview.
To manage backups, seeManage backups.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-12-15 UTC.