Cloud Spanner in Google Cloud: A Database That Refuses to Choose Between Scale and Correctness

Cloud Spanner in Google Cloud: A Database That Refuses to Choose Between Scale and Correctness

A beginner-friendly guide to what Cloud Spanner is, how it stays consistent across the planet, how to design for it, and when it is the right tool.

Imagine a bank with branches in Mumbai, London and New York. A customer transfers money from an account in one city to an account in another. Every branch must agree, instantly and forever, on exactly how much money each account holds. If the London branch briefly believed the money was still there while New York believed it had arrived, chaos would follow. For decades, building a database that could be spread across the world and still always tell the same truth was considered nearly impossible. Cloud Spanner is Google’s answer: a database that can grow to enormous sizes, live in many places at once, and still behave like one careful, trustworthy bookkeeper.

1First, What Is a Database and Why Do We Need Different Kinds?

Before Spanner makes sense, we need a few basic ideas.

A database is an organized memory

A database is a program whose job is to store information safely and give it back quickly when asked. Online shops keep their products and orders in one. Banks keep balances in one. Games keep player scores in one. The program must never lose data, and it must answer questions fast.

Relational databases and tables

A relational database stores information in tables, much like spreadsheets. A “customers” table has one row per customer, and an “orders” table has one row per order. Tables are linked by shared values, such as a customer number. You ask questions using a language called SQL. Relational databases have been trusted for decades because they follow strict rules that keep data correct.

ACID: the promise of correctness

The rules are often summarized by the word ACID. Atomic means a group of changes either all happen or none do. Consistent means the data always follows your rules. Isolated means two people changing data at the same time do not trip over each other. Durable means once the database says “saved,” the data survives crashes and power cuts.

Simple Analogy

Think of moving money between two piggy banks. Atomic means you never take coins out of the first piggy bank without putting them in the second. If you are interrupted halfway, the whole move is undone, and no coins vanish into thin air.

The scaling problem

Traditional relational databases usually live on one main machine. When traffic grows, the usual fix is to buy a bigger machine, which has a limit and a high price. Another approach is to split data across many machines, but that is difficult and often forces you to give up some of those precious ACID guarantees. A different family of databases, often called NoSQL, scales across many machines easily but often relaxes consistency rules. Teams were forced to choose: grow big or stay correct.

2So, What Is Cloud Spanner?

A fully managed database that combines relational correctness with horizontal scale.

Cloud Spanner is Google Cloud’s fully managed, horizontally scalable relational database. It supports SQL, tables, indexes and full ACID transactions, yet it can spread data across many machines and, if you wish, across multiple regions of the world, without giving up strong consistency. Google describes the central promise simply: you get the familiar comfort of a relational database and the growth ability of a distributed one in a single service.

Spanner began inside Google, where it was built to run huge internal systems that could not tolerate lost or inconsistent data. Google published a famous research paper about it in 2012, and the cloud version became available to customers in 2017. That means the design has years of real, large-scale use behind it.

Simple Analogy

Think of a library. A small-town library has one librarian who knows where every book is. A giant national library network has many buildings. Spanner is like a national library network where, no matter which building you walk into, the catalog is perfectly up to date and every librarian agrees on where each book is right now.

2012
Google publishes the Spanner research paper
2017
Cloud Spanner becomes available to customers
99.999%
Availability target for multi-region configurations
!
Common Misconception

Spanner is not just “a bigger Cloud SQL.” It is built on a different design, made of many cooperating machines rather than one main server. That difference is what gives it scale and global reach, and it is also why some habits from small databases need adjusting.

3Core Building Blocks You Must Know

A short dictionary of Spanner words.

Term 1

Instance

The unit of capacity and location you create. It decides where your data lives and how much computing power you have.

Term 2

Database

A set of tables and other objects that live inside an instance. One instance can hold several databases.

Term 3

Instance Configuration

The choice of geography: a single region, two regions, or several regions spread across a continent or the world.

Term 4

Node and Processing Unit

The measure of compute capacity. One node equals 1,000 processing units, and you can start with a fraction of a node.

Term 5

Split

A chunk of a table’s rows that Spanner can move or divide automatically to balance the load across machines.

Term 6

Replica

A copy of your data kept in a different zone or region so that a failure never loses anything.

Term 7

Primary Key

The value that uniquely identifies each row. In Spanner it also decides how rows are spread across machines, so it matters a lot.

Term 8

TrueTime

Google’s special clock system that lets machines around the world agree on the order of events with very small, known uncertainty.

4Architecture: How Spanner Is Built

Many cooperating machines that look like one database from the outside.

Compute and storage are separated

Spanner separates the machines that do the work of running queries from the distributed file system that stores the bytes. This lets Spanner add or remove computing power without copying all your data around, and lets storage grow on its own. It is one reason scaling feels smooth.

Data is cut into splits

Spanner slices each table into contiguous ranges of rows, called splits, based on the primary key. A busy or growing split can be divided into two, and splits can be moved to less busy machines. This all happens automatically in the background. You never decide manually where a row lives.

Every split is replicated

Each split is copied to several replicas in different zones, and in multi-region setups, in different regions. The replicas use a consensus method called Paxos to agree on every change. One replica acts as a leader for the split and coordinates writes, while the others follow. If the leader fails, the group quickly elects a new one, usually without the application noticing.

flowchart TD
    APP[Your Application] --> CL[Spanner Client Library]
    CL --> FE[Spanner API Layer]
    FE --> S1[Split A: Leader]
    FE --> S2[Split B: Leader]
    subgraph Z1[Zone 1]
        S1
    end
    subgraph Z2[Zone 2]
        R1[Split A: Replica]
        S2
    end
    subgraph Z3[Zone 3]
        R2[Split A: Replica]
        R3[Split B: Replica]
    end
    S1 -.consensus.- R1
    S1 -.consensus.- R2
    S2 -.consensus.- R3
        
FIG 1 — Data is cut into splits, and every split is copied across zones that vote on each change
Simple Analogy

Imagine three clerks in different offices who each keep an identical ledger. Before any entry is written, at least two of the three must say “yes, I agree.” Even if one clerk is sick, the ledger stays correct, because the other two still form a majority.

5TrueTime: The Secret Ingredient

How machines on opposite sides of the planet agree on what happened first.

Ordering events is a hard problem in distributed systems. Two machines in different countries have clocks that drift apart by tiny amounts. If you cannot trust the clocks, you cannot be sure which of two changes happened first, and without that, strong consistency is out of reach.

Google solved this with TrueTime. Its data centers contain special time sources, namely GPS receivers and atomic clocks, which keep every machine’s clock very close to true time. Crucially, TrueTime does not pretend to be perfect. It reports time as a small window, saying “the true time is somewhere between this moment and that moment.” The window is usually only a few milliseconds wide.

When Spanner commits a change, it picks a timestamp and then briefly waits until it is certain that timestamp is truly in the past everywhere, a trick called commit wait. Because of this short pause, any transaction that starts after another has finished is guaranteed to see its effects. This gives what experts call external consistency, a very strong promise: the order the database presents is the same as the real-world order in which things happened.

Simple Analogy

Imagine a race with judges in many cities who must agree on the finishing order. If their watches disagree a little, they could argue. Spanner gives every judge a watch that says “the time is between 10:00:00.001 and 10:00:00.005” and has them wait out that small window before announcing the result, so nobody can ever dispute the order.

i
Why You Care

You never touch TrueTime directly. But it is the reason a query in Tokyo and a query in Frankfurt can both see a perfectly consistent picture of your data, and the reason Spanner can honestly promise strong consistency while being globally distributed.

6Choosing Where Your Data Lives: Instance Configurations

The geography decision is the most important one you make when creating an instance.

Regional Configuration

Data is replicated across three zones inside one region. It survives the loss of a zone and offers a 99.99 percent availability target. This is the simple, lower-cost choice for applications whose users are mostly in one area.

Dual-Region Configuration

Data is replicated across two regions in the same country, which helps meet rules about keeping data inside national borders while surviving the loss of an entire region.

Multi-Region Configuration

Data is replicated across several regions, for example within a continent or across continents. It offers a 99.999 percent availability target, tolerates the loss of a whole region, and serves users near any of the regions with fast reads. Writes need agreement across regions, so they are slightly slower than in a regional setup.

Types of replicas

Not every copy plays the same role. Read-write replicas can vote and hold the leader role. Read-only replicas serve reads close to users but do not vote on writes. Witness replicas hold no data for reading, but they cast votes so the group can reach a majority. The exact mix depends on the configuration you choose.

ConfigurationSurvivesBest forTrade-off
RegionalLoss of a zoneApps with users mostly in one areaA region-wide outage is not covered
Dual-regionLoss of a regionData residency rules within one countryMore cost than regional
Multi-regionLoss of a regionGlobal or mission-critical appsHighest cost, slightly slower writes
!
Plan Carefully

Choose your configuration with care. Moving data from one configuration to another is possible but takes planning and effort, so decide based on where your users are, your availability goals and any legal rules about data location.

7Capacity, Nodes and Autoscaling

How you tell Spanner how much power you need.

Spanner’s compute capacity is measured in nodes or, for finer control, processing units. One node equals 1,000 processing units, and you can begin with as few as 100 processing units, which is a tenth of a node. That makes it affordable to start small for a test or a modest application and grow later.

Capacity is what handles your queries. More capacity means more reads and writes per second and more room to run heavy queries. You can change capacity at any time without downtime and without moving your data by hand. Google also offers managed autoscaling that adds or removes capacity based on how busy the instance is, so you do not need to watch dashboards all day.

1

Start with a sensible baseline

Estimate your normal traffic and choose enough capacity to keep processor use comfortably below its limit.

2

Watch processor utilization

Spanner reports how busy the instance is. Google recommends keeping it well under the ceiling so there is headroom for spikes and for recovery after a failure.

3

Let autoscaling help

Set a minimum and maximum, and let the service add capacity when load rises and remove it when load falls.

4

Review regularly

Revisit your limits after product launches, marketing events and seasonal peaks so cost and performance stay balanced.

Simple Analogy

Capacity is like the number of cashiers in a supermarket. Too few and the queue grows long. Too many and you are paying idle staff. Autoscaling is a manager who watches the queue and opens or closes counters throughout the day.

8Designing Your Data: Keys, Tables and Interleaving

Good design is the biggest factor in whether Spanner feels fast and affordable.

Why primary keys matter so much

In a small database, the primary key is mostly a label. In Spanner, rows are stored in sorted key order, and splits are cut along that order. If your keys always increase, such as a number that counts upward or a timestamp, every new row lands at the very end of the table. That means one split receives all the writes while the others sit idle. This problem is called a hotspot, and it wastes the distributed power you are paying for.

The fix is to choose keys that spread writes out. Common approaches include random unique identifiers, adding a small shuffled prefix to the key, or using a sequence designed to be well-distributed. The goal is that new rows land all over the table rather than at one end.

Interleaved tables keep family together

Often, rows from one table naturally belong with rows from another, such as an order and its line items. Spanner lets you interleave a child table inside its parent so that related rows are stored physically next to each other. Reading an order together with all its items then touches one place instead of many, which makes queries faster and cheaper.

Simple Analogy

Imagine a school filing cabinet. Filing student folders strictly by enrolment date means every new student goes into the very last drawer, which becomes jammed while the others stay empty. Filing them by a scrambled code spreads them across all drawers. Interleaving is like putting each student’s report cards inside their own folder rather than in a separate cabinet across the hall.

Other design tools

Secondary indexes let you search by columns other than the primary key. Foreign keys protect the links between tables. Schema changes can be made while the database stays online, and Spanner applies them in the background. As with any database, keep your design as simple as it can be, and avoid creating indexes you do not use, since each one costs storage and slows writes a little.

!
Common Mistake

Carrying over an auto-incrementing number as the primary key from an old database. It feels natural but creates a write hotspot in Spanner. Always rethink key design when migrating.

9Transactions and Reads

The different ways of reading and writing, and what each one costs.

Type 1

Read-Write Transaction

Reads and changes data with full ACID protection. It uses locks so concurrent transactions do not conflict. Use it when you must change data safely.

Type 2

Read-Only Transaction

Reads a consistent snapshot without taking locks. Several reads inside it see the same moment in time, and it does not block writers.

Type 3

Strong Read

A single read that always returns the very latest committed data, no matter where it is served from.

Type 4

Stale Read

A read that accepts data that is a few seconds old. It can be served from the nearest replica, so it is faster and cheaper. Perfect for dashboards and browsing pages.

Type 5

Partitioned Operations

Special large-scale reads and bulk updates that split the work across many machines for big maintenance jobs and analytics.

The most important lesson is to match the tool to the job. If a page only displays a product list, a slightly stale read is perfectly fine and much faster for users far from the leader replica. If you are charging a customer, you want a full read-write transaction. Using the lightest option that is still correct keeps your application quick and your bill small.

sequenceDiagram
    participant App as Application
    participant Lead as Leader Replica
    participant Rep as Other Replicas
    App->>Lead: Begin read-write transaction
    Lead->>Lead: Lock the rows involved
    Lead->>Rep: Propose the change
    Rep-->>Lead: Majority agrees
    Lead->>Lead: Pick timestamp and commit wait
    Lead-->>App: Commit confirmed
        
FIG 2 — A write: the leader locks rows, gets a majority vote and commits at a trusted timestamp
i
Practical Tip

Keep read-write transactions short and small. The longer a transaction holds locks, the more likely it is to collide with others and need a retry. Spanner’s client libraries handle retries for you, but fewer collisions mean better speed.

10Speaking to Spanner: SQL Dialects and Features

You talk to Spanner in a language you probably already know.

Spanner supports SQL in two flavors, called dialects. The first is GoogleSQL, the same family of SQL used across many Google products. The second is a PostgreSQL interface, which lets teams who know PostgreSQL reuse a large portion of their skills, tools and drivers. You choose the dialect when you create a database, and it cannot be switched afterwards for that database, so decide early.

Over time Google has also added capabilities beyond plain tables, including change streams, which let other systems follow every change made to the data, full-text search, and support for graph-style and vector-style queries for modern applications. Because the product keeps evolving, check the current documentation to see which features are available in your chosen edition and dialect.

Feature 1

Change Streams

A live feed of inserts, updates and deletes that other systems can read, useful for analytics pipelines and event-driven designs.

Feature 2

Secondary Indexes

Extra lookup paths so you can find rows quickly by something other than the primary key.

Feature 3

Search and Vector Capabilities

Newer abilities for text search and similarity search, which support modern recommendation and AI-powered features.

Feature 4

Federated Queries

The ability to combine Spanner data with data that lives in other Google Cloud analytics services in a single question.

i
Editions

Spanner is offered in different editions with different feature sets and pricing. The names and what each includes can change, so confirm the current edition table in Google Cloud’s documentation before you decide which one fits your needs.

11Spanner Compared With Other Google Cloud Databases

Choosing the right tool is half the battle.

DatabaseTypeScale patternGood for
Cloud SpannerRelational, distributedScales out for reads and writes, globallyMission-critical systems needing scale and strong consistency
Cloud SQLRelational, managed traditional enginesMostly scales up on one primary, with read copiesStandard applications with moderate size
AlloyDBRelational, PostgreSQL-compatibleScales up with read poolsHigh-performance PostgreSQL workloads
BigtableWide-column NoSQLScales out massivelyHuge volumes of simple, fast key-based data such as time series
FirestoreDocument NoSQLScales automaticallyMobile and web apps with flexible document data
BigQueryAnalytical warehouseScales for large analysisReporting and analytics over huge datasets, not transactions
Simple Analogy

Choosing a database is like choosing a vehicle. A bicycle (a small database) is perfect for short trips. A family car is right for most journeys. A cargo ship (Spanner) is overkill for the corner shop, but unbeatable when you must move enormous amounts reliably across oceans.

i
Rule of Thumb

If a single well-sized database comfortably serves your needs today and for the foreseeable future, a simpler service is usually cheaper and easier. Consider Spanner when you expect to outgrow one machine, need very high availability, or need consistent data across regions.

12Lifecycle: From Idea to Running Database

What actually happens when a team adopts Spanner.

1

Understand the requirements

Decide how much data, how many operations per second, where users are, and how much downtime or data loss the business can accept.

2

Choose configuration and edition

Pick regional, dual-region or multi-region, a SQL dialect, and the edition whose features match your needs.

3

Design the schema

Select distributed-friendly primary keys, decide which tables to interleave and which indexes to create.

4

Create the instance and database

Set the starting capacity, set up access permissions and create the tables.

5

Load or migrate data

Use import and migration tools, often with a period of running old and new systems side by side to validate results.

6

Test performance and failure

Run realistic load tests, look for hotspots, and rehearse what happens when capacity is stretched.

7

Go live and operate

Switch traffic over, monitor closely, tune capacity, and revisit the design as the application grows.

flowchart LR
    A[Requirements] --> B[Configuration and edition]
    B --> C[Schema design]
    C --> D[Create instance]
    D --> E[Load data]
    E --> F[Load test]
    F --> G[Go live]
    G -.-> C
        
FIG 3 — The adoption journey, with a feedback loop back to schema design

13Backup, Recovery and Reliability

Replication protects against hardware failure. Backups protect against everything else.

Because every change is copied to several zones or regions, Spanner already survives the loss of machines, zones and, in multi-region setups, whole regions without losing committed data. But replication also copies mistakes: if someone deletes the wrong rows, every replica faithfully deletes them too. For that reason you need separate recovery tools.

Tool 1

Backups

Consistent copies of a database taken on demand or on a schedule, stored with a chosen retention period and restorable into a new database.

Tool 2

Point-in-Time Recovery

The ability to look at or restore data as it was at a moment in the recent past, within a retention window of up to several days, ideal for undoing accidental changes.

Tool 3

Export and Import

Moving data out to files in Cloud Storage and back in again, useful for archives and for moving between projects.

Tool 4

Multi-Region Replication

Automatic copies across regions that provide resilience to large-scale outages.

Simple Analogy

Replication is like having three identical notebooks written at the same time. If one burns, you still have two. But if you write a wrong number, all three show it. A backup is a photocopy of the notebook taken yesterday, so you can recover the page as it was before the mistake.

!
Common Mistake

Believing that high availability replaces backups. They solve different problems. Always configure backups and test a restore, so you know exactly how long recovery takes.

14Security

Layers of defense around your most valuable data.

Who may come in: identity and access

Access is controlled with Google Cloud’s identity and access management. You can grant people and applications narrow roles, such as permission to only read from one database. Spanner also offers fine-grained access control, which lets you limit access down to specific tables or columns for particular roles. The guiding rule is least privilege: give only the access that is truly needed.

Protecting data at rest and in transit

Data stored in Spanner is encrypted by default, and traffic is encrypted as it travels. If your rules require it, you can use your own encryption keys managed in Google Cloud’s key management service, which gives you control over when keys are rotated or disabled.

Keeping the perimeter tight

Network features such as private connectivity and service perimeters can limit how Spanner can be reached, reducing the chance of data leaving your trusted boundary. Audit logs record who did what, helping with investigations and compliance reviews.

Compliance

Google Cloud supports many industry standards and regional regulations, and data location choices in Spanner can help with residency rules. Compliance is shared work: the platform provides the controls, and you must configure and use them correctly.

flowchart TD
    A[Identity and IAM roles] --> B[Fine-grained access to tables and columns]
    B --> C[Private connectivity and service perimeters]
    C --> D[Encryption at rest and in transit]
    D --> E[Customer-managed keys optional]
    E --> F[Audit logs and monitoring]
        
FIG 4 — Layered security for Spanner, from who can enter to who is recorded

15Monitoring and Performance Tuning

Knowing what the database is feeling.

Spanner reports metrics to Google Cloud’s monitoring tools: processor utilization, request rates, latency, storage use and more. Built-in introspection features help you find the slowest queries, spot hotspots and see which parts of the data are under pressure. Query statistics and a query plan explorer show how a query is executed so you can improve it.

Watch processor utilization

This is the main signal for whether capacity is sufficient. Sustained high values mean it is time to add capacity or fix an inefficient query.

Track latency, not just averages

Averages hide the slowest requests. Look at the slowest few percent, because those are the experiences users complain about.

Look for hotspots

If one part of the table is far busier than the rest, revisit your key design. More capacity will not fix a design that sends all traffic to one place.

Find and fix the costly queries

A single poorly written query that scans a whole table can consume more capacity than thousands of well-written ones. Add the right index or rewrite the query.

i
Practical Tip

Set alerts on utilization and latency before launch, not after the first incident. Tuning under pressure is much harder than tuning in calm.

16Understanding Costs

A pay-for-what-you-provision model with a few moving parts.

Spanner charges mainly for compute capacity, billed by the node or processing unit for each hour it exists, and for the amount of data stored. You also pay for backup storage and for network traffic that leaves a region in certain situations. Multi-region configurations cost more than regional ones because they hold more copies and use more resources. Different editions also have different prices. Because prices change, always use Google Cloud’s pricing page and calculator for current figures.

Start small

Because capacity can begin at a fraction of a node, you can prototype affordably and increase it as real usage appears.

Use autoscaling

Let capacity follow demand so you do not pay for peak capacity around the clock.

Prefer the lightest read that is correct

Stale reads from nearby replicas and read-only transactions use fewer resources than full read-write transactions.

Fix expensive queries first

Optimizing a few heavy queries often saves more money than adding nodes.

Clean up old data and backups

Storage and backups accumulate quietly. Set retention periods and remove data that no longer needs to be kept.

17Where Spanner Shines in the Real World

The kinds of problems Spanner was built for.

Financial systems and payments

Ledgers, balances and transfers where every cent must be exact and the system must stay available around the clock.

Online gaming and global player data

Player profiles, inventories and purchases that must stay consistent as millions of players join from many countries, with sudden spikes at launches and events.

Retail and inventory

Stock counts and orders that must be accurate across warehouses and stores, so the same last item is never sold twice.

Telecommunications and large customer platforms

Huge volumes of subscriber and billing records that need steady performance and no scheduled downtime.

Google’s own systems

Spanner was created to run important internal Google systems, including parts of its advertising infrastructure, which is a big reason for its focus on correctness at scale.

“Spanner lets you stop choosing between a database that grows and a database you can trust.”

18Advantages and Trade-offs

Honest strengths and honest limits.

Advantages

  • Strong consistency and full ACID transactions even across many machines and regions.
  • Horizontal scaling for both reads and writes without manual sharding.
  • Very high availability targets, up to 99.999 percent for multi-region setups.
  • Fully managed: replication, failover, upgrades and most maintenance happen without downtime.
  • Familiar SQL, with GoogleSQL and PostgreSQL interface options.
  • Flexible starting size and online capacity changes.

Disadvantages / Trade-offs

  • Costs more than a simple single-server database for small workloads.
  • Schema design needs distributed thinking; poor key choices cause hotspots.
  • Writes across regions need agreement, so they are slower than in a single location.
  • Some features of traditional databases may behave differently or be unavailable, so migrations need testing.
  • Tied to Google Cloud, so moving elsewhere later requires real effort.
i
Choosing Wisely

Spanner is a precision tool for demanding jobs. For a modest application, a simpler managed database is often the wiser, cheaper choice. Pick Spanner for the problems it is uniquely good at, not by default.

19Best Practices and Anti-Patterns

Lessons from teams who have gone before you.

Best practices at a glance

1

Choose keys that spread writes

Avoid ever-increasing keys. Use random identifiers or other well-distributed designs.

2

Interleave tightly related data

Store parents and children together so common queries touch fewer places.

3

Keep transactions short

Do the minimum work inside a transaction to reduce lock conflicts.

4

Use the right read type

Use stale or read-only reads wherever fresh data is not essential.

5

Leave headroom in capacity

Run well below the utilization ceiling so spikes and failures do not cause slowdowns.

6

Back up and test restores

Schedule backups, use point-in-time recovery wisely, and practice recovery before you need it.

Anti-patterns to avoid

ANTI-PATTERN-01 Avoid
Problem

Using an auto-incrementing number or a timestamp as the first part of the primary key.

Why It’s Harmful

All new rows land at the end of the table, creating a hotspot that wastes the machines you pay for.

Correct Approach

Use distributed-friendly keys such as random unique identifiers or a shuffled prefix.

ANTI-PATTERN-02 Avoid
Problem

Choosing Spanner for a tiny application with no growth or availability needs.

Why It’s Harmful

You pay for power and guarantees you will never use, and take on design rules you did not need.

Correct Approach

Match the database to the real requirements, and choose simpler services when they are enough.

ANTI-PATTERN-03 Avoid
Problem

Running instances at near-maximum utilization to save money.

Why It’s Harmful

There is no room for traffic spikes or for the extra work after a failure, so latency rises and errors appear at the worst moment.

Correct Approach

Keep comfortable headroom and use autoscaling to follow demand.

ANTI-PATTERN-04 Avoid
Problem

Treating replication as a substitute for backups.

Why It’s Harmful

Mistaken deletions and bad updates are copied to every replica, so replication alone cannot undo them.

Correct Approach

Configure backups and point-in-time recovery, and rehearse restores regularly.

20Frequently Asked Questions

Q1Is Cloud Spanner a SQL or a NoSQL database?

It is a relational SQL database with the horizontal scaling that people usually associate with NoSQL systems. It supports tables, SQL and ACID transactions.

Q2What is the CAP theorem and how does Spanner relate to it?

The CAP idea says that during a network split a distributed system must choose between consistency and availability. Spanner chooses consistency during such a split, but its careful engineering, private network and replication make real-world unavailability extremely rare, which is why it can still publish very high availability targets.

Q3Do I need to shard my data manually?

No. Spanner splits, moves and balances data automatically. Your job is to design good primary keys so the automatic process has something useful to work with.

Q4Can I start small?

Yes. Capacity can start at a fraction of a node and be increased at any time without downtime.

Q5Which should I choose, regional or multi-region?

Choose regional if your users are concentrated in one area and a zone-level failure is your main concern. Choose multi-region when you need the highest availability, protection from a regional outage, or fast reads for users in several areas.

Q6What is a hotspot?

A hotspot is a small part of the data that receives most of the traffic, so one machine is overloaded while others are idle. It is usually caused by primary keys that increase in order.

Q7Does Spanner support PostgreSQL?

Spanner offers a PostgreSQL interface that lets many PostgreSQL skills, drivers and tools be reused, although it is not a full copy of PostgreSQL, so check supported features before migrating.

Q8How does Spanner handle failures?

Each split is stored on several replicas that agree on every change. If a machine or zone fails, a replica group elects a new leader and continues serving, usually with only a brief pause that client libraries handle through retries.

Q9Can I run analytics on Spanner data?

Yes, within limits. Spanner offers features that let analytical tools read data without disturbing your live application, and change streams can feed a data warehouse. For heavy reporting over very large datasets, a warehouse such as BigQuery is usually the better home.

Q10Is it difficult to migrate to Spanner?

Migration is very doable but needs planning, especially around primary keys, data types and any features that differ from your current database. Google provides migration tools and guidance, and testing with real data is essential.

21Summary and Key Takeaways

Cloud Spanner brings together two things that were long thought to be incompatible: the strict correctness of a relational database and the unlimited growth of a distributed system. It does this through automatic splitting of data, replication with majority agreement, and TrueTime, Google’s globally synchronized clock. As a fully managed service, it removes much of the operational burden, but it still rewards good design, especially in primary keys and in the choice of read and transaction types. Use it where scale, availability and consistency truly matter, protect it with backups and security layers, watch its capacity and costs, and choose simpler tools when your needs are modest.

Key Takeaways

  • Relational and scalable — Spanner offers SQL, tables and ACID transactions together with horizontal scaling across machines and regions.
  • TrueTime enables global consistency — bounded clock uncertainty and commit wait give external consistency, so everyone sees the same ordered truth.
  • Replication through voting — each split is copied across zones or regions and agrees on changes by majority, so failures rarely cause data loss or long outages.
  • Configuration is a key decision — regional, dual-region and multi-region trade cost and write speed for resilience and reach.
  • Key design is everything — avoid ever-increasing keys, interleave related tables, and keep transactions short to avoid hotspots and conflicts.
  • Backups are still required — replication handles hardware failure, while backups and point-in-time recovery handle human mistakes.
  • Right tool for the job — choose Spanner for mission-critical, large or global workloads, and simpler databases when they are enough.