Restore from a backup

This page describes Spanner restoration operations and explains how torestore a database. For more information about database restoration inSpanner, seeRestoreoverview.

You can restore a Spanner database by using the following:

  • In the Google Cloud console.
  • Using the Google Cloud CLI.
  • Using the client libraries.
  • Using theREST orRPCAPIs.

Before you begin

  • The gcloud CLI examples on this page make the followingassumptions:

    gcloudconfigsetcore/projectPROJECT_ID
    *   You have an instance named`test-instance` and a database named`example-db`.
  • To get the permissions that you need to restore a database from a backup, ask your administrator to grant you the following IAM roles on the instance:

    Note:IAM basic roles might also contain permissions to restore a database from a backup. You shouldn't grant basic roles in a production environment, but you can grant them in a development or test environment.

Restore a database from a backup

Console

  1. Go to the Spanner Instances page in theGoogle Cloud console.

Go to the Spanner Instances page

  1. Click the instance containing the database to open itsOverviewpage.

  2. Click the database to open itsOverview page.

  3. In the navigation pane, clickBackup/Restore.

  4. Click theActions button for your selected backup, then selectRestore.

  5. Fill out the form and click theRestore button.

To check the progress of the operation, see the progress indicator, as shownin the operations page:

Screenshot of progress indicator showing56%

If the operation takes too long, you can cancel it. For more information,seeCancel a long-running instanceoperation.

Note: If you are restoring a database from a backup or a copied backup, therestore operation appears in the instance containing the restored database,not the instance containing the backup.

gcloud

To restore a database, usegcloud spannerdatabases restore:

gcloudspannerdatabasesrestore--async\--destination-instance=test-instance--destination-database=example-db-restored\--source-instance=test-instance--source-backup=example-db-backup-6\--encryption_type=google-managed-encryption

Usage notes:

  • The command returns immediately because of the--async flag. Withoutthe flag, the command will wait for the restore operation to complete.
  • If the source and destination instances are different, they must havethe sameinstanceconfiguration.
  • If the destination database already exists, the operation will fail.
  • The possible values forencryption_type areUSE_DATABASE_ENCRYPTION,GOOGLE_DEFAULT_ENCRYPTION, orCUSTOMER_MANAGED_ENCRYPTION. If you useCUSTOMER_MANAGED_ENCRYPTION, you must specify akmsKeyName.

Client libraries

The following code sample restores a database from agiven backup and waits for the restore operation (an operation withRestoreDatabaseMetadata) tocomplete. The restored database is created in the same instance as thebackup. Once complete, the sample retrieves and prints some restoreinformation from the database.

C++

voidRestoreDatabase(google::cloud::spanner_admin::DatabaseAdminClientclient,std::stringconst&project_id,std::stringconst&instance_id,std::stringconst&database_id,std::stringconst&backup_id){google::cloud::spanner::Databasedatabase(project_id,instance_id,database_id);google::cloud::spanner::Backupbackup(database.instance(),backup_id);autorestored_db=client.RestoreDatabase(database.instance().FullName(),database.database_id(),backup.FullName()).get();if(!restored_db)throwstd::move(restored_db).status();std::cout <<"Database";if(restored_db->restore_info().source_type()==google::spanner::admin::database::v1::BACKUP){autoconst&backup_info=restored_db->restore_info().backup_info();std::cout <<" " <<backup_info.source_database() <<" as of "              <<google::cloud::spanner::MakeTimestamp(backup_info.version_time()).value();}std::cout <<" restored to " <<restored_db->name();std::cout <<" from backup " <<backup.FullName();std::cout <<".\n";}

C#

usingGoogle.Cloud.Spanner.Admin.Database.V1;usingGoogle.Cloud.Spanner.Common.V1;usingGoogle.LongRunning;usingSystem;publicclassRestoreDatabaseSample{publicRestoreInfoRestoreDatabase(stringprojectId,stringinstanceId,stringdatabaseId,stringbackupId){// Create the DatabaseAdminClient instance.DatabaseAdminClientdatabaseAdminClient=DatabaseAdminClient.Create();InstanceNameparentAsInstanceName=InstanceName.FromProjectInstance(projectId,instanceId);BackupNamebackupAsBackupName=BackupName.FromProjectInstanceBackup(projectId,instanceId,backupId);// Make the RestoreDatabase request.Operation<Database,RestoreDatabaseMetadata>response=databaseAdminClient.RestoreDatabase(parentAsInstanceName,databaseId,backupAsBackupName);Console.WriteLine("Waiting for the operation to finish");// Poll until the returned long-running operation is complete.varcompletedResponse=response.PollUntilCompleted();if(completedResponse.IsFaulted){Console.WriteLine($"Database Restore Failed: {completedResponse.Exception}");throwcompletedResponse.Exception;}RestoreInforestoreInfo=completedResponse.Result.RestoreInfo;Console.WriteLine($"Database {restoreInfo.BackupInfo.SourceDatabase} was restored "+$"to {databaseId} from backup {restoreInfo.BackupInfo.Backup} "+$"with version time {restoreInfo.BackupInfo.VersionTime}");returnrestoreInfo;}}

Go

import("context""fmt""io""regexp"database"cloud.google.com/go/spanner/admin/database/apiv1"adminpb"cloud.google.com/go/spanner/admin/database/apiv1/databasepb")funcrestoreBackup(ctxcontext.Context,wio.Writer,db,backupIDstring)error{adminClient,err:=database.NewDatabaseAdminClient(ctx)iferr!=nil{returnerr}deferadminClient.Close()matches:=regexp.MustCompile("^(.*)/databases/(.*)$").FindStringSubmatch(db)ifmatches==nil||len(matches)!=3{returnfmt.Errorf("Invalid database id %s",db)}instanceName:=matches[1]databaseID:=matches[2]backupName:=instanceName+"/backups/"+backupID// Start restoring backup to a new database.restoreOp,err:=adminClient.RestoreDatabase(ctx,&adminpb.RestoreDatabaseRequest{Parent:instanceName,DatabaseId:databaseID,Source:&adminpb.RestoreDatabaseRequest_Backup{Backup:backupName,},})iferr!=nil{returnerr}// Wait for restore operation to complete.dbObj,err:=restoreOp.Wait(ctx)iferr!=nil{returnerr}// Newly created database has restore information.backupInfo:=dbObj.RestoreInfo.GetBackupInfo()ifbackupInfo!=nil{fmt.Fprintf(w,"Source database %s restored from backup %s\n",backupInfo.SourceDatabase,backupInfo.Backup)}returnnil}

Java

staticvoidrestoreBackup(DatabaseAdminClientdbAdminClient,StringprojectId,StringinstanceId,StringbackupId,StringrestoreToDatabaseId){BackupNamebackupName=BackupName.of(projectId,instanceId,backupId);Backupbackup=dbAdminClient.getBackup(backupName);// Initiate the request which returns an OperationFuture.System.out.println(String.format("Restoring backup [%s] to database [%s]...",backup.getName(),restoreToDatabaseId));try{RestoreDatabaseRequestrequest=RestoreDatabaseRequest.newBuilder().setParent(InstanceName.of(projectId,instanceId).toString()).setDatabaseId(restoreToDatabaseId).setBackup(backupName.toString()).build();OperationFuture<com.google.spanner.admin.database.v1.Database,RestoreDatabaseMetadata>op=dbAdminClient.restoreDatabaseAsync(request);// Wait until the database has been restored.com.google.spanner.admin.database.v1.Databasedb=op.get();// Get the restore info.RestoreInforestoreInfo=db.getRestoreInfo();BackupInfobackupInfo=restoreInfo.getBackupInfo();System.out.println("Restored database ["+db.getName()+"] from ["+restoreInfo.getBackupInfo().getBackup()+"] with version time ["+backupInfo.getVersionTime()+"]");}catch(ExecutionExceptione){throwSpannerExceptionFactory.newSpannerException(e.getCause());}catch(InterruptedExceptione){throwSpannerExceptionFactory.propagateInterrupt(e);}}

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}=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';// Creates a clientconstspanner=newSpanner({projectId:projectId,});// Gets a reference to a Cloud Spanner Database Admin Client objectconstdatabaseAdminClient=spanner.getDatabaseAdminClient();// Restore the databaseconsole.log(`Restoring database${databaseAdminClient.databasePath(projectId,instanceId,databaseId,)} from backup${backupId}.`,);const[restoreOperation]=awaitdatabaseAdminClient.restoreDatabase({parent:databaseAdminClient.instancePath(projectId,instanceId),databaseId:databaseId,backup:databaseAdminClient.backupPath(projectId,instanceId,backupId),});// Wait for restore to completeconsole.log('Waiting for database restore to complete...');awaitrestoreOperation.promise();console.log('Database restored from backup.');const[metadata]=awaitdatabaseAdminClient.getDatabase({name:databaseAdminClient.databasePath(projectId,instanceId,databaseId),});console.log(`Database${metadata.restoreInfo.backupInfo.sourceDatabase} was restored `+`to${databaseId} from backup${metadata.restoreInfo.backupInfo.backup} `+'with version time '+`${newPreciseDate(metadata.restoreInfo.backupInfo.versionTime,).toISOString()}.`,);

Note: The old client library interface code samples for Node.js are archived inGitHub.

PHP

use Google\Cloud\Spanner\Admin\Database\V1\Client\DatabaseAdminClient;use Google\Cloud\Spanner\Admin\Database\V1\RestoreDatabaseRequest;/** * Restore a database from a backup. * Example: * ``` * restore_backup($projectId, $instanceId, $databaseId, $backupId); * ``` * @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. */function restore_backup(    string $projectId,    string $instanceId,    string $databaseId,    string $backupId): void {    $databaseAdminClient = new DatabaseAdminClient();    $backupName = DatabaseAdminClient::backupName($projectId, $instanceId, $backupId);    $instanceName = DatabaseAdminClient::instanceName($projectId, $instanceId);    $request = new RestoreDatabaseRequest([        'parent' => $instanceName,        'database_id' => $databaseId,        'backup' => $backupName    ]);    $operationResponse = $databaseAdminClient->restoreDatabase($request);    $operationResponse->pollUntilComplete();    $database = $operationResponse->operationSucceeded() ? $operationResponse->getResult() : null;    $restoreInfo = $database->getRestoreInfo();    $backupInfo = $restoreInfo->getBackupInfo();    $sourceDatabase = $backupInfo->getSourceDatabase();    $sourceBackup = $backupInfo->getBackup();    $versionTime = $backupInfo->getVersionTime()->getSeconds();    printf(        'Database %s restored from backup %s with version time %s' . PHP_EOL,        $sourceDatabase, $sourceBackup, $versionTime    );}

Note: The old client library interface code samples for PHP are archived inGitHub.

Python

defrestore_database(instance_id,new_database_id,backup_id):"""Restores a database from a backup."""fromgoogle.cloud.spanner_admin_database_v1importRestoreDatabaseRequestspanner_client=spanner.Client()database_admin_api=spanner_client.database_admin_api# Start restoring an existing backup to a new database.request=RestoreDatabaseRequest(parent=database_admin_api.instance_path(spanner_client.project,instance_id),database_id=new_database_id,backup=database_admin_api.backup_path(spanner_client.project,instance_id,backup_id),)operation=database_admin_api.restore_database(request)# Wait for restore operation to complete.db=operation.result(1600)# Newly created database has restore information.restore_info=db.restore_infoprint("Database{} restored to{} from backup{} with version time{}.".format(restore_info.backup_info.source_database,new_database_id,restore_info.backup_info.backup,restore_info.backup_info.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 of where to restore"# backup_id = "Your Spanner backup ID"require"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_idjob=database_admin_client.restore_databaseparent:instance_path,database_id:database_id,backup:backup_pathputs"Waiting for restore backup operation to complete"job.wait_until_done!database=database_admin_client.get_databasename:db_pathrestore_info=database.restore_infoputs"Database#{restore_info.backup_info.source_database} was restored to#{database_id} from backup#{restore_info.backup_info.backup} with version time#{restore_info.backup_info.version_time}"

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.