Installation
Install as Agent Plugin
Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install spanner-basics@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin spanner-basics v1.0.0 follows the Agent Plugins spec.
Install with the gh extension
gh skills-hub install spanner-basics Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/spanner-basics/ Extract the ZIP to .github/skills/ in your repo. The folder name must match spanner-basics for Copilot to auto-discover it.
Skill Files (11)
SKILL.md 3.8 KB
---
name: spanner-basics
metadata:
version: "1.1.2"
category: Databases
description: >-
Assists in provisioning instances and databases, designing performant schemas, and querying data in Cloud Spanner on Google Cloud. Use when designing primary keys, writing SQL queries or client library code, or diagnosing performance issues.
---
# Spanner Basics
This skill provides core workflows and guidance for administering and developing with Cloud Spanner on Google Cloud, a fully managed, mission-critical database service offering global transactional consistency and automatic, synchronous replication for high availability.
## Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read [Usage Attribution](references/attribution.md). For commands executed
directly in the terminal (never in generated scripts, Terraform, or user code),
prefix `gcloud` with
`CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:spanner-basics)"`
and append `agent-skills/1.0 (skill:spanner-basics)` to `User-Agent` headers.
## Core Principles
- **Performance First:** Spanner scales horizontally. Efficiency is tied to
Primary Key design. Always warn against using monotonically increasing/decreasing
values (like sequential timestamps) as the first part of a primary key to avoid hotspots.
- **Schema Design:** Prefer interleaved tables for strongly related parent-child data
that is frequently accessed together.
## Safety
> [!CAUTION] **CRITICAL INSTRUCTION:** You MUST obtain explicit user confirmation before making any non-emulator database changes (DML or DDL) or destructive operations (such as dropping tables, indexes, or any other Spanner resources). Do not execute them automatically; instead, output the command (e.g., `gcloud spanner databases ddl update`) and ask for explicit user approval.
> When database access is unavailable or authentication fails, do not block on trying to verify the existence of the instance, database, or table. Assume the provided resources exist and directly generate the DDL commands.
## Common Workflows
### Schema Evolution & DDL
1. Use `gcloud spanner databases ddl update` to apply schema updates (such as CREATE, ALTER, or DROP tables and indexes).
2. Reference [schema-design.md](references/schema-design.md) for guidelines on primary key selection and interleaved tables.
### Diagnosing Performance Issues
1. Use `SPANNER_SYS` tables to identify slow or resource-intensive queries.
2. For example, query `SPANNER_SYS.QUERY_STATS_TOP_HOUR` to find queries with the highest CPU usage.
## Reference Directory
- [Core Concepts](references/core-concepts.md): Explanation of Spanner internals, architecture, and design.
- [CLI Usage](references/cli-usage.md): Essential `gcloud spanner` command-line operations for managing instances and databases.
- [IAM Security](references/iam-security.md): Roles, permissions, and data governance best practices for Spanner.
- [Client Library Usage](references/client-library-usage.md): Using Google Cloud client libraries for Spanner (Java, Go, Python, Node.js).
- [Terraform Usage](references/terraform-usage.md): Infrastructure as Code examples for provisioning Spanner instances and databases.
- [MCP Usage](references/mcp-usage.md): Using the Spanner remote MCP server.
- [PostgreSQL Dialect](references/postgresql-dialect.md): Best practices and examples for using the PostgreSQL interface in Spanner.
- [Queues Usage](references/queues-usage.md): Cloud Spanner Queues: mental model, design constraints, and links related to transactional message queues.
- [Schema Design](references/schema-design.md): Guidelines on primary key selection and interleaved tables for performance.
If you need product information that's not found in these references, use the
`search_documents` tool of the Developer Knowledge MCP server.
references/
attribution.md 1.8 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:spanner-basics)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include `agent-skills/1.0 (skill:spanner-basics)` in the `User-Agent`
header. If a `User-Agent` header is already specified, append this string to
the end of it rather than overwriting existing `User-Agent` data — the
collection pipeline parses the `agent-skills/<version>` and `skill:<name>`
tokens, so any rewording breaks attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:spanner-basics)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
cli-usage.md 1.3 KB
# CLI Usage
Common `gcloud` commands for interacting with Spanner. For instructions on how
to install the Google Cloud SDK, see
[Install the Google Cloud SDK](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt).
## Instances
### List Instances
```bash
gcloud spanner instances list
```
### Create Instance
```bash
# Fixed nodes
gcloud spanner instances create my-instance \
--config=regional-us-central1 \
--description="My Instance" \
--nodes=1
# Autoscaler
gcloud spanner instances create my-autoscaled-instance \
--config=regional-us-central1 \
--description="My Autoscaled Instance" \
--autoscaling-min-nodes=1 \
--autoscaling-max-nodes=3
```
## Databases
### List Databases
```bash
gcloud spanner databases list --instance=my-instance
```
### Create Database
```bash
gcloud spanner databases create my-database --instance=my-instance
```
## Execute Query
```bash
gcloud spanner databases execute-sql my-database --instance=my-instance --sql="SELECT 1"
```
## Backups
### Create Backup
```bash
gcloud spanner backups create my-backup \
--instance=my-instance \
--database=my-database \
--retention-period=7d
```
## Operations
### List Operations
```bash
gcloud spanner operations list --instance=my-instance
```
client-library-usage.md 3.5 KB
# Client Library Usage
Instructions on how to install the Google Cloud SDK can be found at
[Install the Google Cloud SDK](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt).
## Client Libraries
Google Cloud client libraries provide an idiomatic way to interact with Spanner
from your preferred programming language.
### Python
- **Installation:**
```bash
pip install google-cloud-spanner
```
- **Usage Example:**
```python
from google.cloud import spanner
spanner_client = spanner.Client()
instance = spanner_client.instance("my-instance-id")
database = instance.database("my-database-id")
with database.snapshot() as snapshot:
results = snapshot.execute_sql("SELECT 1")
for row in results:
print(row)
```
- [Python Reference](https://docs.cloud.google.com/python/docs/reference/spanner/latest.md.txt)
### Java
- **Maven Dependency:**
```xml
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-spanner</artifactId>
</dependency>
```
- **Usage Example:**
```java
SpannerOptions options = SpannerOptions.newBuilder().build();
Spanner spanner = options.getService();
DatabaseClient dbClient = spanner.getDatabaseClient(DatabaseId.of(options.getProjectId(), "my-instance-id", "my-database-id"));
ResultSet resultSet = dbClient.singleUse().executeQuery(Statement.of("SELECT 1"));
while (resultSet.next()) {
System.out.println(resultSet.getLong(0));
}
```
- [Java Reference](https://docs.cloud.google.com/java/docs/reference/google-cloud-spanner/latest/overview.md.txt)
### Node.js
- **Installation:**
```bash
npm install @google-cloud/spanner
```
- **Usage Example:**
```javascript
const {Spanner} = require("@google-cloud/spanner");
const spanner = new Spanner({projectId: "my-project-id"});
const instance = spanner.instance("my-instance-id");
const database = instance.database("my-database-id");
const [rows] = await database.run({sql: "SELECT 1"});
```
- [Node.js Reference](https://docs.cloud.google.com/nodejs/docs/reference/spanner/latest)
### Go
- **Installation:**
```bash
go get cloud.google.com/go/spanner
```
- **Usage Example:**
```go
ctx := context.Background()
client, err := spanner.NewClient(ctx, "projects/my-project-id/instances/my-instance-id/databases/my-database-id")
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
defer client.Close()
iter := client.Single().Query(ctx, spanner.Statement{SQL: "SELECT 1"})
defer iter.Stop()
```
- [Go Reference](https://docs.cloud.google.com/go/docs/reference/cloud.google.com/go/spanner/latest.md.txt)
## Additional Libraries
### LangChain Integration
Spanner integrates with LangChain to help you build LLM-powered applications.
- **Vector Store**: Use `SpannerVectorStore` to store and search vector
embeddings.
- **Document Loader**: Use `SpannerLoader` to load data from Spanner.
- **Chat Message History**: Use `SpannerChatMessageHistory` to store
conversation history.
For more information, see the
[Spanner guide for LangChain](https://docs.cloud.google.com/spanner/docs/langchain.md.txt).
### Spring Data Spanner
For Java applications using the Spring Framework, the Spring Data Spanner module
provides a familiar Spring Data interface.
For more information, see
[Add Spring Data Spanner to your application](https://docs.cloud.google.com/spanner/docs/adding-spring.md.txt).
core-concepts.md 1.1 KB
# Core Concepts
Cloud Spanner is a fully managed, mission-critical database service that
combines the benefits of relational database structure with non-relational
horizontal scale. It offers transactional consistency at global scale,
automatic, synchronous replication for high availability, and support for two
SQL dialects: GoogleSQL and PostgreSQL.
## Key Features
* **Global Scale**: Spanner scales horizontally across rows, regions, and
continents.
* **Strong Consistency**: Spanner provides external consistency for
transactions, ensuring that all reads see the most recent writes.
* **Multi-Dialect**: Supports GoogleSQL (ANSI 2011 with extensions) and
PostgreSQL.
* **Multi-Model**: Integrates relational, key-value, graph (Spanner Graph),
and search capabilities.
## Architectures
Spanner is designed to support a wide range of workloads, from small-scale
applications to global, mission-critical, high-transaction workloads requiring
strong consistency and up to 99.999% availability.
## Pricing
For up-to-date pricing information, please see the official
[Spanner Pricing](https://cloud.google.com/spanner/pricing) page.
iam-security.md 1.2 KB
# IAM Security
Common IAM roles for Spanner and security best practices.
## Predefined IAM Roles
* **Cloud Spanner Admin** (`roles/spanner.admin`): Full control over all
Spanner resources.
* **Cloud Spanner Database Admin** (`roles/spanner.databaseAdmin`): Full
control over databases, backups, and operations.
* **Cloud Spanner Database Reader** (`roles/spanner.databaseReader`): Can read
data and execute queries.
* **Cloud Spanner Database User** (`roles/spanner.databaseUser`): Can read and
write data.
* **Cloud Spanner Viewer** (`roles/spanner.viewer`): Can view Spanner
resources but cannot access data.
## Security Best Practices
* **Principle of Least Privilege**: Grant only the minimum necessary
permissions to users and service accounts.
* **Use Service Accounts**: For applications, use service accounts instead of
personal user accounts.
* **VPC Service Controls**: Use VPC Service Controls to help mitigate data
exfiltration risks.
* **CMEK**: Use Customer-Managed Encryption Keys (CMEK) if required by your
security policy.
> [!CAUTION] Granting `roles/spanner.admin` gives full access to all Spanner
> resources in the project. Use with caution.
mcp-usage.md 1.5 KB
# MCP Usage
Spanner supports Model Context Protocol (MCP) to connect your database to LLM
agents.
## Connecting to MCP Server
You can use pre-built tools provided by Spanner to connect your IDE or
application to Spanner using MCP.
For detailed instructions, see the official documentation:
[Connect your IDE to Spanner using MCP](https://docs.cloud.google.com/spanner/docs/use-spanner-mcp.md.txt)
## MCP Tools for Spanner
The Spanner MCP server exposes the following tools to LLM agents:
- `get_instance`: Get information about a specific Spanner instance.
- `list_instances`: List all Spanner instances in a given project.
- `list_configs`: List instance configurations available in a project.
- `get_config`: Get information about a specific instance configuration.
- `create_instance`: Create a new Spanner instance.
- `update_instance`: Update a Spanner instance.
- `create_database`: Create a database in a given instance.
- `get_database_ddl`: Retrieve the database schema (DDL).
- `list_databases`: List all databases in a given instance.
- `create_session`: Create a session in a database for query execution.
- `execute_sql`: Execute a SQL statement (both DQL and DML supported).
- `execute_sql_readonly`: Execute a SQL query statement in a single-use read-only transaction.
- `commit`: Commit a transaction.
- `update_database_schema`: Update the schema for a given database.
- `get_operation`: Get the status of a long-running operation.
For more details, see the [Spanner MCP reference](https://docs.cloud.google.com/spanner/docs/reference/mcp.md.txt).
postgresql-dialect.md 0.9 KB
# PostgreSQL Dialect Support
Spanner provides PostgreSQL dialect support by expressing Spanner database
features through a subset of open source PostgreSQL dialect constructs.
## Key Considerations
* **Portability**: Easier migration to other PostgreSQL databases if needed.
* **Familiarity**: Leverages existing knowledge of PostgreSQL syntax and
tools.
* **Ecosystem**: Supports tools like `psql` and PostgreSQL drivers (via
PGAdapter).
## Features and Extensions
Spanner includes extensions to support Spanner-specific features within the
PostgreSQL dialect:
- Interleaved tables
- Time to live (TTL)
- Query hints
## Limitations
Spanner does not support some open source PostgreSQL features:
- Triggers
- `SERIAL`
- Transactional DDL
- User-defined data types and operators
For more information, see
[The PostgreSQL language in Spanner](https://docs.cloud.google.com/spanner/docs/reference/postgresql/overview.md.txt).
queues-usage.md 10.8 KB
# Cloud Spanner Queues Usage
Cloud Spanner Queues provide an integrated, transactional messaging system built directly into
Spanner. They let applications perform asynchronous and scheduled work reliably without running
separate queuing infrastructure.
**Prerequisite:** Queues require the **Enterprise** or **Enterprise Plus** Spanner edition.
## Table of Contents
- [Authoritative Public Documentation](#authoritative-public-documentation): Lines 18-33
- [Mental Model](#mental-model): Lines 37-54
- [Canonical Syntax & Operations](#canonical-syntax--operations): Lines 58-158
- [Constraints Worth Knowing Before You Design](#constraints-worth-knowing-before-you-design): Lines 162-179
- [Observability](#observability): Lines 183-196
- [Agent Verification Checklist](#agent-verification-checklist): Lines 200-213
## Authoritative Public Documentation
The DDL, the receive and renew-lease table-valued functions (TVFs), their parameters, defaults, and
limits evolve. Fetch the current pages (or query the Developer Knowledge MCP server via
`search_documents`) before writing or reviewing Spanner queue code:
| Page | Use it for |
| :--- | :--- |
| [Queues Overview](https://docs.cloud.google.com/spanner/docs/queues/queues-overview.md.txt) | Concepts, delivery semantics, when to use queues. |
| [Use Spanner Queues](https://docs.cloud.google.com/spanner/docs/queues/queues-using.md.txt) | Task-by-task how-to: create, send, receive, renew, ack. |
| [Queue Examples](https://docs.cloud.google.com/spanner/docs/queues/queues-examples.md.txt) | End-to-end examples and worker patterns. |
| [At-Most-Once Processing](https://docs.cloud.google.com/spanner/docs/queues/queues-at-most-once.md.txt) | Achieving at-most-once processing. |
| [GoogleSQL DDL Reference](https://docs.cloud.google.com/spanner/docs/reference/standard-sql/data-definition-language.md.txt) | Authoritative GoogleSQL queue DDL grammar and options. |
| [PostgreSQL DDL Reference](https://docs.cloud.google.com/spanner/docs/reference/postgresql/data-definition-language.md.txt) | Authoritative PostgreSQL-dialect queue DDL grammar. |
| [Fine-Grained Access Control for Queues](https://docs.cloud.google.com/spanner/docs/fgac-queues.md.txt) | Fine-grained access control for queues. |
| [Spanner Quotas & Limits](https://docs.cloud.google.com/spanner/quotas.md.txt) | Queue quotas and limits, including receiver concurrency. |
---
## Mental Model
These properties define how queues behave and are what the rest of a design should rest on:
- **Transactional.** Sending and acknowledging happen inside ordinary read-write transactions, so
they commit atomically with your table writes. This is the whole point of queues living in
Spanner: no dual-write problem between a database and an external broker.
- **At-least-once delivery.** A message is redelivered until acknowledged. Leases reduce duplicate
work but do not guarantee exclusivity, so **consumers must be idempotent**.
- **Exactly-once acknowledgment.** Acking is a transactional delete of the message row, so a given
message can only be acked once.
- **Short leases.** A delivered message is leased briefly (default 10 seconds). The worker
acknowledges it or renews the lease before expiry, or it is redelivered. Long work should renew in
a loop, or checkpoint by acking and re-sending with a future delivery time.
- **Scheduled delivery.** Every message can carry a future delivery time (`DeliverTime` in GoogleSQL,
`deliver_time` in PostgreSQL), which removes the need for polling or a separate scheduler.
- **A schema object.** A queue has a primary key, appears in `INFORMATION_SCHEMA`, can be
interleaved in a parent table, and can be inspected with an ordinary `SELECT`.
---
## Canonical Syntax & Operations
### 1. Create a Queue (`CREATE QUEUE`)
Define a primary key (avoid monotonic leading keys; use a UUID or interleave under a high-cardinality
parent table) and a non-nullable `Payload` column. `DeliverTime` (`deliver_time` in PostgreSQL) is
created automatically by Spanner and must not be declared in `CREATE QUEUE`.
```sql
-- GoogleSQL
CREATE QUEUE UserTasks (
UserId INT64 NOT NULL,
MessageId STRING(36) NOT NULL,
Payload BYTES(MAX) NOT NULL
) PRIMARY KEY (UserId, MessageId),
INTERLEAVE IN PARENT Users ON DELETE CASCADE;
-- PostgreSQL dialect
CREATE QUEUE usertasks (
userid bigint NOT NULL,
messageid varchar(36) NOT NULL,
payload bytea NOT NULL,
PRIMARY KEY (userid, messageid)
) INTERLEAVE IN PARENT users ON DELETE CASCADE;
```
### 2. Send a Message (`INSERT` or Client Library `Send` Mutation)
Insert into the queue inside the same read-write transaction as your application table updates:
```sql
-- GoogleSQL (immediate or scheduled delivery via DeliverTime)
INSERT INTO UserTasks (UserId, MessageId, Payload, DeliverTime)
VALUES (@userId, @messageId, @payload, TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL 10 MINUTE));
-- PostgreSQL dialect
INSERT INTO usertasks (userid, messageid, payload, deliver_time)
VALUES ($1, $2, $3, CURRENT_TIMESTAMP + INTERVAL '10 MINUTE');
```
Client libraries also provide `spanner.Send("UserTasks", key, payload, spanner.WithDeliveryTime(t))`
(Go) and `Mutation.newSendBuilder("UserTasks")` (Java).
### 3. Receive Messages (`RECEIVE_<QueueName>`)
Stream messages using `ExecuteStreamingSQL` with a **strong, single-use, read-only transaction**:
```sql
-- GoogleSQL
SELECT UserId, MessageId, Payload, DeliverTime,
SpannerLeaseExpirationTimestamp, SpannerLeaseToken, SpannerLastBatchMessage
FROM RECEIVE_UserTasks(max_duration => '20m', max_batch_size => 20);
-- PostgreSQL dialect
SELECT userid, messageid, payload, deliver_time,
spanner_lease_expiration_timestamp, spanner_lease_token, spanner_last_batch_message
FROM spanner.receive_usertasks(20, NULL, '20m');
```
### 4. Renew Leases (`RENEWLEASE_<QueueName>`) and Acknowledge (`DELETE` / `Ack`)
```sql
-- GoogleSQL: Renew lease (returns SpannerOldLeaseToken, SpannerNewLeaseToken, SpannerLeaseExpirationTimestamp)
SELECT * FROM RENEWLEASE_UserTasks(lease_tokens => [@leaseToken]);
-- GoogleSQL: Acknowledge message transactionally (guard with ASSERT_ROWS_MODIFIED 1)
DELETE FROM UserTasks WHERE UserId = @userId AND MessageId = @messageId ASSERT_ROWS_MODIFIED 1;
-- PostgreSQL dialect: Renew lease and Acknowledge
SELECT * FROM spanner.renewlease_usertasks(lease_tokens => ARRAY[$1]);
DELETE FROM usertasks WHERE userid = $1 AND messageid = $2 ASSERT_ROWS_MODIFIED 1;
```
Client libraries also provide `spanner.Ack("UserTasks", key)` (Go) and
`Mutation.newAckBuilder("UserTasks")` (Java), which fail the transaction if the message row was
already deleted.
#### Handle Long-Running Work
When processing can outlast the lease (default 10 seconds), use one of two patterns:
- **Renew in a loop.** In a separate thread or goroutine, call
`RENEWLEASE_<QueueName>` periodically (for example, every 5 seconds) with the
latest lease token. When the work finishes, ack the message in the same
transaction as the resulting writes.
- **Ack and reschedule.** On arrival, ack the message and, in the same
transaction, send a new message with a delivery time beyond the expected
processing time. Process the work, then ack the new message.
```sql
-- GoogleSQL: ack and reschedule in one read-write transaction
DELETE FROM UserTasks WHERE UserId = @userId AND MessageId = @messageId ASSERT_ROWS_MODIFIED 1;
INSERT INTO UserTasks (UserId, MessageId, Payload, DeliverTime)
VALUES (@userId, @newMessageId, @payload, TIMESTAMP_ADD(CURRENT_TIMESTAMP(), INTERVAL 30 MINUTE));
```
Ack and reschedule needs no renewal loop, and a crash is covered because the new
message is redelivered at its delivery time. If the initial ack succeeds, it
achieves at-most-once processing. It is also the recommended checkpoint for
tasks lasting minutes to hours: store task state in a table and have each
rescheduled message point to the latest checkpoint.
---
## Constraints Worth Knowing Before You Design
Durable behaviors that shape architecture, and that are easy to get wrong:
- **A queue holds only its primary key columns and `Payload`.** No extra columns. Application state
belongs in regular tables.
- **Keep payloads small (< 4 KB).** Small messages take a faster delivery path. Store blobs in a
table or Cloud Storage and enqueue a key.
- **Receive queries are restricted.** They must be strong, single-use, read-only, and streamed, and
they cannot be joined against other tables. Filtering is supported.
- **Lease tokens rotate on renewal.** A successful renewal returns a new token (`SpannerNewLeaseToken`
/ `spanner_new_lease_token`) that supersedes the old one; carry it forward or the next renewal
fails. If `SpannerNewLeaseToken` is `NULL`, the message is no longer renewable.
- **Guard your ack.** A plain delete silently succeeds when the row is already gone, hiding a lost
race. Always use `ASSERT_ROWS_MODIFIED 1` or the dedicated `Ack` mutation.
- **Receiver concurrency is quota-limited** per project per region; exceeding it returns
`RESOURCE_EXHAUSTED`. Size worker fleets with that in mind.
- **Retention is a row deletion policy (TTL),** the same mechanism used for tables.
---
## Observability
Queue metrics are published to Cloud Monitoring under the **`spanner.googleapis.com/queue/*`**
prefix, on the `spanner_instance` resource, labeled by `database` and `queue`. For the current list
of names, kinds, and units, search the metrics reference for `queue/`:
[Spanner Cloud Monitoring Metrics](https://docs.cloud.google.com/monitoring/api/metrics_gcp.md.txt#gcp-spanner)
The signal to alert on is the age of the oldest unacknowledged message: it is the end-to-end measure
of a queue falling behind. Send and ack counts show whether consumers keep up with producers, and
lease expirations point at slow handlers, crashes, or a missing renewal loop.
There are no queue-specific `SPANNER_SYS` tables. Receive queries and ack transactions show up in
the general introspection views, and tagging those statements with request tags makes them easy to
find. See [Spanner Introspection Overview](https://docs.cloud.google.com/spanner/docs/introspection.md.txt).
---
## Agent Verification Checklist
- [ ] **Docs consulted:** Current queue pages were fetched; syntax was not guessed from memory.
- [ ] **Edition:** Instance is Enterprise or Enterprise Plus.
- [ ] **Dialect:** GoogleSQL versus PostgreSQL-dialect syntax and system column names match the
target database.
- [ ] **Schema:** No columns beyond the primary key and `Payload` (`DeliverTime` is implicit);
payloads are kept small (< 4 KB).
- [ ] **Receive:** Strong, single-use, read-only, streamed; no joins on the TVF.
- [ ] **Leases:** Work that can outlast the 10s lease renews in a loop and carries the rotated
token, or uses an ack-and-reschedule checkpoint instead.
- [ ] **Ack:** Guarded with `ASSERT_ROWS_MODIFIED 1` or `Ack` mutation, and committed in the same
transaction as the resulting application writes.
- [ ] **Idempotency:** Redelivery is safe. schema-design.md 3.4 KB
# Schema Design
Best practices for schema design in Spanner to ensure performance and
scalability.
## Primary Key Design
To avoid creating hotspots, carefully choose a primary key. A common cause of
hotspots is using a key that monotonically increases or decreases (such as a
timestamp) as the first part of the primary key. This directs all insert traffic
to a single server, creating a bottleneck.
### Hotspot Prevention Techniques
#### Use a Universally Unique Identifier (UUID)
* Recommend using **UUID Version 4** (uses random values).
* Eliminates hotspots because they don't keep locality between related
records.
* Stored in a `UUID` column.
#### Bit-reversed Sequential Values
* Avoid sequentially increasing/decreasing numerical primary keys.
* Bit-reverse sequential values to distribute primary key values evenly across
the key space.
* Spanner supports bit-reversed sequences.
#### Swap the Order of Keys
* Spread writes over the key space more uniformly by putting a
high-cardinality, non-monotonic column first.
* Example: Order by `UserId` first, then chronological `LastAccess` timestamp.
#### Hash the Unique Key
* Create a column that contains the hash of the actual unique key.
* Use the hash column as the primary key to spread writes across logical
shards.
### Descending Order for Timestamp Keys
Consider using descending order (`DESC`) for timestamp keys if:
* You want to read the most recent history and are reading the parent row in
an interleaved table.
* You are reading sequential entries in reverse chronological order (e.g.,
most recent N events).
## When to Use an Interleaved Index
* Avoid creating non-interleaved indexes on columns whose values are
monotonically increasing or decreasing (like non-primary key timestamps).
* Use an **interleaved index** where last access rows are interleaved under
the corresponding user row.
## Data Types
* **GoogleSQL**: `ARRAY`, `BOOL`, `BYTES`, `DATE`, `ENUM`, `FLOAT32`,
`FLOAT64`, `INT64`, `JSON`, `NUMERIC`, `PROTO`, `STRING`, `STRUCT`,
`TIMESTAMP`, `UUID`.
* **PostgreSQL**: `array`, `bool`, `bytea`, `date`, `float4`, `float8`,
`int8/bigint`, `jsonb`, `numeric`, `timestamptz`, `uuid`, `varchar/text`.
All types except `FLOAT32`, `ARRAY`, `JSON`, `PROTO`, and `STRUCT` are valid for
primary keys.
## Performance Checklist (Agent Verification)
When reviewing or generating schema-related code, verify the following:
- [ ] **Hotspot Prevention:** Ensure the first part of the primary key is NOT
a monotonically increasing or decreasing value (like a sequential ID or
timestamp). If it is, recommend a UUID (v4), bit-reversed sequence, or
hashing.
- [ ] **Interleaved Tables:** Verify if strongly related parent-child data
that is frequently accessed together is structured using interleaved tables
(`INTERLEAVE IN PARENT`).
- [ ] **Interleaving Depth:** Limit interleaving depth. Spanner supports up to
7 levels of interleaving, but keeping it to a minimum avoids excessive
overhead.
- [ ] **Index Design:** Ensure secondary indexes are created for frequent
query patterns. If sorting by a timestamp is needed, check if the index
should use descending order (`DESC`).
- [ ] **Data Types:** Check that the chosen data types are optimal and valid
for the column's purpose (e.g., `FLOAT32`, `ARRAY`, `JSON`, and `STRUCT`
cannot be used as primary keys).
terraform-usage.md 0.9 KB
# Terraform Usage
You can use Terraform to build, change, and version Spanner infrastructure.
## Google Cloud Terraform Provider
The Google Cloud Terraform Provider supports the following Spanner resources:
- `google_spanner_instance`
- `google_spanner_database`
- `google_spanner_instance_iam`
- `google_spanner_database_iam`
## Example Usage
The following Terraform configuration creates a Spanner instance and a database.
```terraform
resource "google_spanner_instance" "example" {
name = "example-instance"
config = "regional-us-central1"
display_name = "Example Instance"
nodes = 1
}
resource "google_spanner_database" "example" {
instance = google_spanner_instance.example.name
name = "example-database"
}
```
For more information, see the official
[Google Cloud Terraform Provider documentation](https://registry.terraform.io/providers/hashicorp/google/latest/docs).
License (Apache-2.0)
Apache-2.0
Source: google/skills
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE