Study guide
7.1 Spanner Keys, Indexes, and Transactions
Google Cloud Professional Cloud Developer Exam
Track your progress as you read
Finished sections get a check mark.
1 Chapter 1: Exam and Compute Platform Decisions
1.1 Current Exam, Sources, and Scenario Method 1.2 Cloud Run Execution and Platform Selection 1.3 GKE Modes and Compute Engine Trade-offs
2 Chapter 2: Container Engineering and API Contracts
2.1 Stateless Microservices and Multi-stage Builds 2.2 Container Hardening, Signals, and Layer Caching 2.3 REST, gRPC, and Protobuf Contracts
3 Chapter 3: gRPC Compatibility and Geographic Routing
3.1 Schema Evolution and gRPC Routing 3.2 Geography, Network Tiers, and Load Balancers 3.3 Serverless NEGs, Sessions, and Edge Controls
4 Chapter 4: API Management and Caching
4.1 API Management & Rate Limiting with Apigee and API Gateway 4.2 Memorystore and Cache Access Patterns 4.3 Cache Invalidation, Capacity, and Failover
5 Chapter 5: Messaging, Task Dispatch, and Orchestration
5.1 Event-Driven Messaging with Cloud Pub/Sub 5.2 Task Queues & Rate Throttling with Cloud Tasks 5.3 Event Routing and Service Orchestration: Eventarc & Cloud Workflows
6 Chapter 6: Resilience and Relational Availability
6.1 Designing Resilient Systems: Circuit Breaking, Retries & Failover 6.2 Cloud SQL Availability and Recovery 6.3 Connection Budgets and Spanner Consistency
7 Chapter 7: Distributed Schemas and NoSQL Data Models
7.1 Spanner Keys, Indexes, and Transactions 7.2 Firestore Data, Indexes, and Transactions 7.3 Bigtable Row Keys and Replication
8 Chapter 8: Object Storage and Application Identity
8.1 Cloud Storage Lifecycle and Signed Access 8.2 Workload Identity and Service Authentication 8.3 Secret Delivery, Rotation, and IAP
9 Chapter 9: Security, Data Integration, and Developer Credentials
9.1 Private Communication, Key Rotation, and Vulnerability Response 9.2 AlloyDB Schemas and BigQuery Ingestion 9.3 CLI Configurations, Local ADC, and Cloud Shell
10 Chapter 10: Managed Development and Automated Tests
10.1 Cloud Workstations and the Container Inner Loop 10.2 Emulating Google Cloud Services & Database Auth Proxies 10.3 Automated Testing Strategies: Unit, Integration, and Mocking
11 Chapter 11: AI Development Tools and Build Pipelines
11.1 AI Coding Assistants, Context, MCP, and Test Review 11.2 Cloud Build Workers and Step Dependencies 11.3 Builders, Substitutions, Triggers, and IAM
12 Chapter 12: Artifact Security and Admission Policies
12.1 Artifact Management and Vulnerability Scanning with Artifact Registry 12.2 Build Provenance and Admission Concepts 12.3 Attestors, Policy Enforcement, and Break-glass
13 Chapter 13: Cloud Run and GKE Deployment Configuration
13.1 Cloud Run Deployment and Scaling Configuration 13.2 Cloud Run CPU, Private Egress, and Secrets 13.3 GKE Workload Controllers and Gateway Routing
14 Chapter 14: Kubernetes Resources, Health, and Progressive Releases
14.1 GKE Resources, OOM Diagnosis, and Autoscaling 14.2 Container Health Probes, Lifecycle Hooks & Graceful Shutdown 14.3 Progressive Delivery: Traffic Splitting, Canary, and Blue/Green Rollouts
15 Chapter 15: Source/Event Deployment and Cloud API Integration
15.1 Source Deployment, Event Receivers, and API Versions 15.2 Client Libraries, Service Enablement, and ADC 15.3 API Responses, Pagination, Caches, and Retries
16 Chapter 16: Tracing, Sampling, and Monitoring
16.1 Trace Context and OpenTelemetry Export 16.2 Custom Spans, Trace Analysis, and Sampling 16.3 Application Metrics, Health Checks & Alerting with Cloud Monitoring
17 Chapter 17: Structured Logs, Routing, and Error Management
17.1 Structured Logs, Trace Correlation, and Queries 17.2 Log Routing, Export Destinations, and Exclusions 17.3 Error Reporting Formats and Regression Handling
18 Chapter 18: Profiling, Generative AI, and Assisted Troubleshooting
18.1 Cloud Profiler Types and Flame Graph Analysis 18.2 Generative AI Integration with the Google Gen AI SDK 18.3 Evidence-Based Troubleshooting with AI Assistance
7.1 Spanner Keys, Indexes, and Transactions
Key Takeaways Explain This Topic AI
High-write monotonic leading keys can hotspot one range; random or bit-reversed keys distribute writes.
STORING columns can make a secondary index cover the requested projection.
Mutation API limits are cumulative per commit, while current DML mutation limits apply per statement; transaction size still matters.
Last updated: October 2026
Spanner Schema Design: Hotspotting & Table Interleaving
In Cloud Spanner, data is automatically split horizontally into chunks called splits based on primary key ranges. Each split is managed by an independent Spanner node. Achieving high throughput requires distributing reads and writes evenly across all splits. ANTI-PATTERN (Monotonically Increasing Key):
- Split 1: [1000 - 1999] (IDLE)
- Split 2: [2000 - 2999] (IDLE)
- Split 3: [3000 - 3999] <=== ALL WRITES HIT HERE (100% CPU HOTSPOT!)
OPTIMIZED PATTERN (Bit-Reversed / UUIDv4 Distributed Keys):
- Split 1: [0000 - 3FFF] <=== 25% Writes
- Split 2: [4000 - 7FFF] <=== 25% Writes
- Split 3: [8000 - BFFF] <=== 25% Writes
- Split 4: [C000 - FFFF] <=== 25% Writes
- The Hotspotting Anti-Pattern
If a table uses a monotonically increasing primary key (such as an auto-increment integer, a sequential sequence, or a current timestamp CURRENT_TIMESTAMP() ), all new inserts will have keys greater than all existing keys. Every insert targets the exact same split at the end of the key space, overwhelming a single node while all other nodes sit idle.
Anti-Hotspotting Solutions
UUIDv4 (Universally Unique Identifiers): Generate random 128-bit UUIDv4 values as primary keys. Random bits ensure uniform distribution across all splits.
Bit-Reversed Sequential Keys: Reverse the binary bits of an auto-incrementing integer sequence using Spanner's built-in BIT_REVERSE() function. Sequential numbers (1, 2, 3...) produce radically dispersed binary values, distributing writes across all splits while preserving numeric compactness.
Hash Prefixing: Prepend a hash of a column attribute or shard ID (an application-computed stable hash bucket) to the primary key.
Table Interleaving
In traditional relational databases, joining a parent table ( Customers ) with a child table ( Orders ) requires cross-server network hops if tables reside on different disks or nodes. Spanner resolves this using Table Interleaving : -- Parent Table
- CREATE TABLE Customers (
- CustomerId STRING(36) NOT NULL,
- FullName STRING(100),
- Email STRING(100)
- ) PRIMARY KEY (CustomerId);
- - Child Table Interleaved in Parent
- CREATE TABLE Orders (
- CustomerId STRING(36) NOT NULL,
- OrderId STRING(36) NOT NULL,
- OrderDate DATE,
- TotalAmount NUMERIC,
- OrderStatus STRING(30)
- ) PRIMARY KEY (CustomerId, OrderId),
- INTERLEAVE IN PARENT Customers ON DELETE CASCADE;
Physical Co-location: Interleaving physically co-locates the child Orders rows directly alongside the parent Customers row in related key ranges to improve locality; large interleaved groups can still be split.
Performance Impact: Joins between Customers and Orders on CustomerId can benefit from locality, but are not guaranteed to have zero network communication, dramatically accelerating query execution and parent-child transactional commits.
- Spanner Secondary Indexes, STORING, and Transactions
- Secondary Indexes and the STORING Clause
A secondary index in Cloud Spanner is implemented as an independent distributed table sorted by the index key. If a query filters on the indexed column but selects columns not present in the index, Spanner must perform an expensive back-join across the network to the base table split.
To eliminate back-joins, use the STORING clause : -- Index without STORING: Requires expensive back-join to fetch TotalAmount
CREATE INDEX OrdersByDate ON Orders(OrderDate);
- - Covering Index with STORING: Eliminates back-joins
- CREATE INDEX OrdersByDateCovering ON Orders(OrderDate)
- STORING (TotalAmount, OrderStatus);
The STORING clause duplicates the specified non-key columns ( TotalAmount , OrderStatus ) into the index split. The query engine satisfies the query entirely from the index split, reducing latency and compute consumption.
Mutation Limits
Cloud Spanner enforces strict limits on transaction size to maintain predictable latency:
Maximum Mutations per Commit: A Mutation API commit permits up to 80,000 mutations , including index effects. Current DML limits apply per statement rather than cumulatively across separate DML statements (where a mutation is an insert, update, or delete of a cell—calculated as rows * columns + index updates ).
Maximum Transaction Size: A commit payload cannot exceed 100 MiB .
Developer Mitigation for Bulk Loads: When ingesting millions of rows, developers must partition data into smaller batches (e.g., 2,000 to 5,000 mutations per batch) and commit them independently, or use the Spanner Dataflow/Bulk Import connectors.
Read-Write vs. Read-Only Transactions
Read-Write Transactions: Provide atomic, externally consistent updates; concurrency-control/isolation options determine locking and conflict behavior. Contending operations can abort and require the entire transaction callback to be retried. Commit wait ensures TrueTime external consistency.
Read-Only Transactions: Never acquire locks and never block incoming writes. They execute using a TrueTime timestamp (strong read or bounded staleness). For analytics, dashboards, and batch exports, developers can choose read-only transactions with a freshness bound suitable for the task (e.g., exact_staleness = 15s ) to read from local replicas without cross-region consensus latency.
Architectural Decision Framework: Cloud SQL vs. Cloud Spanner
Evaluation Dimension Cloud SQL Cloud Spanner
Workload Scale Managed engine instance; limits vary by engine and edition Distributed compute/storage; scale within documented capacity and workload limits
Geographic Scope Regional with cross-region read replicas (async) Native multi-region active-active synchronous replication
Availability SLA Depends on edition and HA configuration 99.99% regional outside Stockholm (99.95% Stockholm); 99.999% dual/multi-region, subject to current SLA terms
Failover RTO Measure recovery and reconnection for the chosen configuration Depends on failure, quorum and application recovery; no universal sub-second RTO
Engine Compatibility Direct MySQL, PostgreSQL, SQL Server compatibility Spanner GoogleSQL or PostgreSQL dialect (proprietary engine)
Primary Key Strategy Standard auto-incrementing sequences permitted Strict anti-hotspotting mandatory (UUIDv4, bit-reversed)
Cost Profile Low baseline cost (runs on modest single VMs) Enterprise baseline cost (minimum 100 processing units / 0.1 node)
Join Optimization Standard relational query optimizer Optimized via Table Interleaving & STORING indexes
Official references checked October 18, 2026: Google Cloud 1 , Google Cloud 2 .