1
---
2
name: spanner-graph-schema-best-practices
3
metadata:
4
version: "1.0.0"
5
category: Databases
6
description: >-
7
Designs, reviews, and optimizes physical table schemas, indexes, and graph
8
topologies for Spanner Graph on Google Cloud. Use when creating a new Spanner
9
Graph schema, selecting node and edge primary key types, optimizing forward,
10
reverse, or per-node Top-K edge traversals, designing interleaved node or edge
11
tables and covering indexes, configuring cascading deletes and row deletion
12
policies (TTL), evaluating schematized versus schemaless dynamic label graphs,
13
or folding 1:1 and N:1 edges into node tables. Don't use for tuning GQL query
14
syntax or execution plans without schema changes (use
15
spanner-graph-query-tuning), or when creating a zero-change graph overlay on
16
existing relational tables (use spanner-relational-to-graph).
17
---
18
19
# Spanner Graph Schema Design & Topology Best Practices
20
21
Design and optimize physical table layouts, primary keys, secondary indexes, and
22
graph topologies for **Spanner Graph** (`CREATE PROPERTY GRAPH`) to maximize
23
performance.
24
25
## Usage Attribution
26
27
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
28
MUST read and follow the instructions in
29
[Usage Attribution](references/attribution.md).
30
31
## Safety & Verification Rules
32
33
- **Obtain Confirmation Before Mutating Remote Databases**: Do not execute
34
`gcloud spanner databases ddl update`, `create`, or `delete` against a remote
35
Spanner instance without explicit user confirmation, because DDL mutations on
36
live databases can trigger long-running schema backfills or break production
37
queries. Always validate candidate DDL on the local Spanner Emulator first or
38
output the DDL commands for user approval.
39
- **Obtain Confirmation Before Changing the Cloud Environment**: Ask the user
40
before running `gcloud services enable`, changing the active project or
41
billing account, or creating or deleting Spanner instances, because these
42
commands change the user's Google Cloud environment and can incur costs.
43
- **Inspect Live Catalog Read-Only**: When reviewing an existing Spanner
44
database, export the schema with `gcloud spanner databases ddl describe
45
{database_id} --instance={instance_id} --project={project_id}` rather than
46
guessing column types or key orders.
47
48
## Prerequisites & Cloud Environment Setup
49
50
Before running `gcloud spanner` or emulator commands, verify that the
51
environment meets these Google Cloud requirements (see `spanner-basics` for
52
general Spanner instance provisioning and MCP setup):
53
54
1. **Google Cloud SDK & Static DDL Fallback**: Verify whether the CLI is
55
installed (do not install `gcloud` without explicit user permission; see
56
[Install the gcloud CLI](https://docs.cloud.google.com/sdk/docs/install-sdk.md.txt)).
57
If `gcloud` or the local emulator is unavailable, generate and review the
58
Spanner Graph DDL statically using the rules and reference templates below.
59
2. **Project, Billing & API Enablement**: Configure the target project (`gcloud
60
config set project {project_id}`), ensure an active billing account is
61
attached (required even when provisioning a free trial instance; see
62
[Spanner pricing](https://cloud.google.com/spanner/pricing) and
63
[Google Cloud pricing](https://cloud.google.com/pricing)), and, after the
64
user confirms, enable the API:
65
```bash
66
gcloud services enable spanner.googleapis.com --project={project_id}
67
```
68
3. **Authentication**: Authenticate with `gcloud auth login` (interactive CLI),
69
`gcloud auth application-default login` (local SDKs), or
70
`GOOGLE_APPLICATION_CREDENTIALS` (service accounts).
71
4. **Required Identity and Access Management (IAM) Roles (Least Privilege)**:
72
- `roles/spanner.databaseReader` (or `roles/spanner.viewer`) to inspect DDL
73
via `gcloud spanner databases ddl describe`.
74
- `roles/spanner.databaseAdmin` to create databases or apply schema updates
75
(`gcloud spanner databases ddl update`).
76
5. **Region & Instance Configuration**: When creating a new instance, select a
77
supported regional or multi-region configuration such as
78
`regional-us-central1` (`gcloud config set spanner/instance {instance_id}`;
79
see [Instance configurations](https://docs.cloud.google.com/spanner/docs/instance-configurations.md.txt)
80
and [Cloud locations](https://cloud.google.com/about/locations)).
81
82
## Terminology Glossary
83
84
Use these canonical terms consistently when reasoning about and explaining
85
Spanner Graph schemas:
86
87
Term | Definition
88
--- | ---
89
**Node table** | A physical Spanner table projected in `NODE TABLES` of `CREATE PROPERTY GRAPH`; each row is one node.
90
**Edge table** | A physical table (or a node table projected a second time under an alias) listed in `EDGE TABLES`; each row is one directed edge from `SOURCE KEY` to `DESTINATION KEY`.
91
**Node type / Edge type** | One node or edge table projection in the property graph, identified by its name or alias (for example, `IpCard AS HasCard` is an edge type).
92
**Label** | The query-time name attached to a node or edge type via `LABEL` (static) or `DYNAMIC LABEL` (schemaless). One type can declare multiple labels, and one label can be shared by multiple types.
93
**Property** | A column or scalar SQL expression (for example, `CAST(...)` or `LOWER(...)`) exposed on a node or edge type via `PROPERTIES (...)` or `DYNAMIC PROPERTIES`.
94
**Folded edge** | A `many-to-{0,1}` or `many-to-1` edge stored as a foreign-key column on the source node table, projected via `{node_table} AS {edge_type}` instead of a separate edge table.
95
**1:N containment child node** | A node table interleaved in its parent node table (`INTERLEAVE IN PARENT`) because each child is owned by exactly one parent; it serves as both a node type and the parent-to-child edge type.
96
**Remote interleaved index** | A secondary index on an edge table co-located with the destination node table via `INTERLEAVE IN {dest_node_table}` (no `PARENT` keyword) to accelerate reverse traversal.
97
**Hub / super node** | A node with thousands or millions of incoming or outgoing edges.
98
99
## Core Schema Design Workflow
100
101
Follow this 5-step workflow when designing a new Spanner Graph schema or
102
optimizing an existing one.
103
104
**MUST READ**: Steps 1–4 below are abbreviated summaries that include only
105
short structural DDL snippets. The complete decision rules, trade-offs, and
106
full multi-table `CREATE TABLE`, `CREATE INDEX`, and `CREATE PROPERTY GRAPH`
107
examples live in the reference guides; before recommending or generating DDL,
108
read [Topology & Edge Folding](references/topology-and-edge-folding.md) (for
109
Steps 1–2) and
110
[Edge Traversal & Indexing](references/edge-traversal-and-indexing.md) (for
111
Steps 3–4).
112
113
### Step 1: Choose Schematized vs. Schemaless Data Management
114
115
Select the graph storage model based on schema stability and query patterns.
116
Read the *Compare schema types* section of the official
117
[Spanner Graph schema design best practices](https://docs.cloud.google.com/spanner/docs/graph/best-practices-designing-schema.md.txt)
118
alongside [Topology & Edge Folding](references/topology-and-edge-folding.md)
119
for the full decision matrix:
120
121
Option | Best For | Key Mechanism
122
--- | --- | ---
123
**Schematized (Default)** | Stable domain models, strong type enforcement, non-JSON native types (`TIMESTAMP`, `INT64`, `NUMERIC`), and single-type quantified paths | Separate typed node/edge tables with explicit `LABEL` and `PROPERTIES (col1, col2)` declarations
124
**Schemaless (Hybrid Properties Design)** | Many node or edge types that are impractical to maintain as separate tables, frequently evolving schemas, polymorphic edges that connect many different node types, or latency-sensitive quantified path queries (`-{1, 3}->`) that span multiple node or edge labels | Single node table and single edge table using `DYNAMIC LABEL (label)` and `DYNAMIC PROPERTIES (properties)`, plus an explicit `PROPERTIES (...)` list that keeps any frequently filtered or indexed columns as typed static properties alongside the `JSON` payload
125
126
If the user hasn't already described their schema and workload, ask before
127
choosing: how many node and edge types they need to maintain (for example, more
128
than 50 node types and 150 edge types), and whether latency-sensitive queries
129
traverse multiple labels (for example, `-[:Transfer|Withdraw]->{1, 3}`) across a
130
large number of intermediate paths (for example, more than 10,000).
131
132
Store `DYNAMIC LABEL` values in lowercase and enforce it with
133
`CHECK (label = LOWER(label))`. Rows with uppercase or mixed-case label values
134
silently get no dynamic label and drop out of labeled `MATCH` patterns (query
135
labels themselves are case-insensitive).
136
137
### Step 2: Optimize Physical Primary Keys & Topology Restructuring
138
139
Before creating secondary indexes, optimize the physical table topology so
140
common traversals execute as local primary-key prefix seeks instead of
141
distributed joins. Read
142
[Topology & Edge Folding](references/topology-and-edge-folding.md) for full
143
multi-table DDL examples and apply these rules:
144
145
1. **Re-Key Standalone Edge Tables by `(src_id, dst_id, [edge_id])`, Enforce
146
`NOT NULL`, and Prefer `INT64` / Native `UUID` Keys**:
147
- Avoid using a synthetic `PRIMARY KEY (edge_id)` as the leading key column
148
on an edge table, because outgoing traversals from a source node cannot
149
seek on `src_id` and must scan the entire table or rely on a secondary
150
index.
151
- Define `PRIMARY KEY ({src_key_cols}, {dst_key_cols}, [{uniquifier_col}])`,
152
declare all primary key and endpoint foreign key columns `NOT NULL` (which
153
eliminates null-check branches in execution plans), and interleave the edge
154
table into the source node table (`INTERLEAVE IN PARENT {source_node_table}
155
ON DELETE CASCADE`):
156
157
```sql
158
CREATE TABLE AccountTransfer (
159
src_id INT64 NOT NULL,
160
dst_id INT64 NOT NULL,
161
transfer_id INT64 NOT NULL,
162
) PRIMARY KEY (src_id, dst_id, transfer_id),
163
INTERLEAVE IN PARENT Account ON DELETE CASCADE;
164
```
165
166
- Prefer `INT64` keys (bit-reversed sequence or random/hashed `INT64`) for
167
node and edge keys on traversal-heavy graphs. If you need UUIDs, use the
168
native `UUID` type rather than `STRING(36)`: 36-byte string keys widen
169
secondary indexes and make multi-hop joins slower and more CPU-intensive
170
than 8-byte `INT64` or 16-byte native `UUID` keys.
171
2. **Advanced — Co-Locate Strict 1:N Containment Child Node Tables
172
(`INTERLEAVE IN PARENT`)**:
173
- **Cardinality Guardrail — Strict `1:N` Containment Only**: Use this
174
advanced technique only when each child node is owned by exactly one
175
parent node and cannot exist without it (strict `1:N` physical
176
containment, such as `IpCard` belonging to one `IpNode`, or `Subnet`
177
belonging to one `Vpc`). If the relationship is many-to-many (`M:N`)—for
178
example, an `IpCard` or `Vrf` that can connect to multiple `IpNode`s—or
179
the child is an independent entity, **never** interleave the child node
180
table under the other node table; keep both as standalone node tables and
181
model the relationship as a dedicated edge table interleaved in the source
182
node table (Step 2.1). Confirm the cardinality with the user before
183
applying this layout.
184
- When strict `1:N` containment applies, prefix the child node's primary key
185
with the parent's primary key and declare `INTERLEAVE IN PARENT
186
{parent_node_table}`. This co-locates parent and child nodes in the same
187
storage split AND lets the child table serve directly as the
188
parent-to-child edge type without a separate edge table:
189
190
```sql
191
CREATE TABLE IpCard (
192
ip_id STRING(64) NOT NULL,
193
card_id STRING(64) NOT NULL,
194
) PRIMARY KEY (ip_id, card_id),
195
INTERLEAVE IN PARENT IpNode ON DELETE CASCADE;
196
-- In CREATE PROPERTY GRAPH:
197
-- NODE TABLES (IpNode KEY (ip_id), IpCard KEY (ip_id, card_id))
198
-- EDGE TABLES (IpCard AS HasCard SOURCE KEY (ip_id) REFERENCES IpNode (ip_id)
199
-- DESTINATION KEY (ip_id, card_id) REFERENCES IpCard (ip_id, card_id))
200
```
201
202
- **Always Reference the Full Composite Key**: Because interleaving changes
203
the child node's primary key to `({parent_key}, {child_key})`, always
204
declare `KEY ({parent_key}, {child_key})` on the child node table and list
205
every key column in any `SOURCE KEY` or `DESTINATION KEY` referencing it.
206
Referencing only `{child_key}` against a 2-column `KEY` is accepted by
207
Spanner and silently matches every row sharing that partial key.
208
3. **Fold `many-to-{0,1}` and `many-to-1` Edges into the Source Node Table**:
209
- When each source node has **at most one** outgoing edge of a given type to
210
a target node (`many-to-{0,1}` or `many-to-1`, such as
211
`(IpNode)-[:ipOnOptical]->(OpticalNode)`), store the target key
212
(`optical_node_id`) as a column directly on the source node table and
213
project that table in both `NODE TABLES` (`IpNode`) and `EDGE TABLES`
214
(`IpNode AS IpOnOpticalEdge`). A `NULL` target key means the node has no
215
such edge (`many-to-0`):
216
217
```sql
218
CREATE TABLE IpNode (
219
ip_id STRING(64) NOT NULL,
220
optical_node_id STRING(64),
221
FOREIGN KEY (optical_node_id) REFERENCES OpticalNode (optical_node_id),
222
) PRIMARY KEY (ip_id);
223
-- In CREATE PROPERTY GRAPH:
224
-- EDGE TABLES (IpNode AS IpOnOpticalEdge
225
-- SOURCE KEY (ip_id) REFERENCES IpNode (ip_id)
226
-- DESTINATION KEY (optical_node_id) REFERENCES OpticalNode (optical_node_id)
227
-- LABEL ipOnOptical)
228
```
229
230
Folding removes a separate edge table to maintain and write. The query
231
speedup is modest and appears only when a query filters on or returns
232
source-node properties, because the node and its edge come from the same
233
row; key-only traversals perform the same as with an interleaved edge
234
table.
235
- **Enforce the Folded Foreign Key, Never `ON DELETE CASCADE`**: Declare the
236
target-key column as an enforced foreign key to the target node table so it
237
can't point to a missing node. `ON DELETE CASCADE` on this foreign key
238
would delete the source node rows, not just their edges; to delete a
239
target node, first set the referencing target keys to `NULL`. Use
240
`NOT ENFORCED` only for target node tables in datasets with high-degree hub
241
nodes, after confirming the trade-off with the user (see Step 3).
242
- **Cardinality Guardrail — Do Not Fold `M:N` Edges into Node Tables**: Never
243
fold a many-to-many (`M:N`) edge into a node table by adding `target_id` to
244
the node's primary key, because doing so duplicates the node row for every
245
connected target and corrupts node-level aggregations like
246
`MATCH (n:Node) RETURN COUNT(n)`. Keep `M:N` relationships in a dedicated
247
edge table interleaved in the source node table.
248
4. **Consolidate 1:1 Subtype Nodes & Fold 1:1 Intermediate Pass-Through Hops**:
249
- Merge fragmented 1:1 subtype tables (e.g., `RouterNode`, `SwitchNode`,
250
`FirewallNode` sharing the same entity key) into a unified node table (such
251
as `DeviceNode`) with a type discriminator column (such as `device_type`).
252
- If there is no need to model an intermediate pass-through node type in the
253
graph, fold 1:1 pass-through intermediate tables (such as a `CableNode`
254
table where each cable only connects two `Router` endpoints via
255
`Router <-[:terminatedBy]- CableNode -[:terminatedBy]-> Router`) directly
256
into a single edge table so each router-to-router step is 1 hop instead of
257
2. Doing so leaves the intermediate node type (`CableNode`) out of the
258
graph schema: its attributes become edge properties, it can no longer be
259
matched as a node (`MATCH (c:CableNode)`), and it cannot have edges of its
260
own. **Confirm with the user that this is desired before choosing this
261
model** (see Section 5.2 of
262
[Topology & Edge Folding](references/topology-and-edge-folding.md) for the
263
before-and-after comparison):
264
265
```sql
266
CREATE TABLE Router (
267
router_id STRING(64) NOT NULL,
268
site_name STRING(128),
269
) PRIMARY KEY (router_id);
270
271
-- Each cable becomes one edge row between its two routers.
272
CREATE TABLE CableLink (
273
router_id STRING(64) NOT NULL,
274
peer_router_id STRING(64) NOT NULL,
275
cable_id STRING(64) NOT NULL,
276
capacity_gbps INT64,
277
FOREIGN KEY (peer_router_id) REFERENCES Router (router_id),
278
) PRIMARY KEY (router_id, peer_router_id, cable_id),
279
INTERLEAVE IN PARENT Router ON DELETE CASCADE;
280
281
CREATE OR REPLACE PROPERTY GRAPH CableGraph
282
NODE TABLES (Router)
283
EDGE TABLES (
284
CableLink
285
SOURCE KEY (router_id) REFERENCES Router (router_id)
286
DESTINATION KEY (peer_router_id) REFERENCES Router (router_id)
287
LABEL cableLink PROPERTIES (cable_id, capacity_gbps)
288
);
289
-- One router-to-router hop: MATCH (a:Router)-[:cableLink]->(b:Router)
290
```
291
292
5. **Align Shared Label Properties and Graph-Wide Property Types**:
293
- When multiple node or edge tables share the same `LABEL`, expose the exact
294
same property names and SQL data types across every table declaring that
295
label. Moreover, across the **entire property graph** (even between
296
unrelated labels or between nodes and edges), any property with the same
297
exposed name must have the same SQL data type (`The property declaration of
298
'id' has type conflicts...`). Use column aliases or scalar SQL expressions
299
such as `CAST({col} AS {target_type}) AS {property_name}` in
300
`PROPERTIES (...)` when underlying column types differ.
301
302
### Step 3: Optimize Forward & Reverse Edge Traversals
303
304
Configure physical co-location, foreign keys, and covering indexes for all
305
remaining edge tables as detailed in
306
[Edge Traversal & Indexing](references/edge-traversal-and-indexing.md):
307
308
1. **Forward Traversal (`(src)-[e]->(dst)`)**:
309
- Interleave the edge table into the source node table (`INTERLEAVE IN PARENT
310
{source_node_table} ON DELETE CASCADE`) and add a `FOREIGN KEY
311
({dst_key_cols}) REFERENCES {dest_node_table} ({dst_key_cols})` on the
312
destination key so the Spanner query optimizer can prune the destination
313
node table scan when queries only need the destination key:
314
315
```sql
316
CREATE TABLE PersonOwnAccount (
317
person_id INT64 NOT NULL,
318
account_id INT64 NOT NULL,
319
create_time TIMESTAMP,
320
FOREIGN KEY (account_id) REFERENCES Account (id),
321
) PRIMARY KEY (person_id, account_id),
322
INTERLEAVE IN PARENT Person ON DELETE CASCADE;
323
```
324
325
- For target node tables in datasets with high-degree **hub / super nodes**
326
(where individual target nodes receive thousands or millions of concurrent
327
incoming edges), consider a table-level informational foreign key (`NOT
328
ENFORCED`, configured on the table's `FOREIGN KEY` constraint rather than
329
per individual node) to avoid write lock contention on hub rows during
330
concurrent edge inserts while preserving optimizer join elimination.
331
Confirm this trade-off with the user first: informational foreign keys
332
don't prevent dangling edges, and because the optimizer uses them by
333
default, queries can return results that don't match the data if an edge
334
points to a missing node. Keep the foreign key enforced when the user needs
335
strict referential integrity.
336
2. **Reverse (`(dst)<-[e]-(src)`) & Any-Direction (`(a)-[e]-(b)`) Traversal**:
337
- Create a **Remote Interleaved Index** keyed by
338
`({dst_key_cols}, {src_key_cols})` with a `STORING ({edge_properties})`
339
clause and `INTERLEAVE IN {dest_node_table}` (without the `PARENT`
340
keyword):
341
342
```sql
343
CREATE INDEX {edge_table}ByDst
344
ON {edge_table} ({dst_id}, {src_id})
345
STORING ({edge_prop_1}, {edge_prop_2}),
346
INTERLEAVE IN {dest_node_table};
347
```
348
349
- **Note on `INTERLEAVE IN PARENT` vs. `INTERLEAVE IN`**: While
350
`INTERLEAVE IN PARENT` on a child table requires exact column *name*,
351
type, and order matching, `INTERLEAVE IN {dest_node_table}` on a secondary
352
index (Remote Index) uses *positional type matching*—so `{dst_id}`
353
co-locates in `{dest_node_table}`'s split even when the column name
354
differs from `{dest_node_table}`'s primary key name.
355
- **Store Non-Key Edge Columns by Default**: Including `{src_id}` in the
356
index key and, by default, adding all non-key edge columns to the `STORING`
357
clause (matching the Spanner Graph UI modeler behavior) enables a 100%
358
index-only scan without back-joining to the base edge table. If the edge
359
table has many or wide columns, discuss with the user which frequently
360
accessed edge properties to keep in `STORING`.
361
- **Undirected Queries on Directed Edges (`-[e:Transfers]-{1,4}`)**: Keep
362
plain any-direction traversal backed by the reverse index above. Don't add
363
a second swapped-key reverse edge type in `CREATE PROPERTY GRAPH` for
364
performance: querying it as a label union
365
(`-[:Transfers|ReverseTransfer]->{1,3}`) forces Spanner to evaluate a union
366
across two edge types at every hop, which is slower than
367
`-[:Transfers]-{1,3}`.
368
- **Mutually Symmetric Relationships (`Friend`, `Peer`) Stored as Directed
369
Pairs**: When an application stores each symmetric relationship as two
370
directed rows (`(user_a, user_b)` and `(user_b, user_a)` in one
371
transaction) under `PRIMARY KEY (src_id, dst_id)`, always query with
372
directed `-[:Friend]->` so outgoing traversals seek a single primary-key
373
prefix (especially beneficial on high-degree nodes). Never query a
374
double-stored edge table with undirected `-[:Friend]-`: because both
375
`(A, B)` and `(B, A)` exist in the table, an undirected pattern matches
376
both rows and returns every neighbor twice (and full-scans the table if no
377
reverse index exists).
378
379
### Step 4: Add Property-Filtering Indexes & Prevent Dangling Edges
380
381
By default, initial schema creation only requires primary keys and
382
topology/reverse-traversal indexes (Steps 2–3); you do not need to index node or
383
edge properties up front. Add the property-filtering indexes in items 1–2 below
384
only when the user's queries filter (`WHERE` / `FILTER`) or sort (`ORDER BY ...
385
LIMIT k`) on specific non-key properties (see Section 3 of
386
[Edge Traversal & Indexing](references/edge-traversal-and-indexing.md)):
387
388
1. **Node Property Filtering Indexes**: Create secondary indexes on node
389
columns frequently used in `WHERE` / `FILTER` clauses. Use `WHERE {col} IS
390
NOT NULL` (NULL-filtered index) for sparse properties to save storage and
391
write overhead:
392
393
```sql
394
CREATE INDEX AccountByNickName ON Account (nick_name) STORING (is_blocked);
395
CREATE INDEX AccountByCloseTime ON Account (close_time) WHERE close_time IS NOT NULL;
396
```
397
398
2. **Edge Property Filtering & Per-Node Top-K Indexes**:
399
- For forward or reverse traversal with edge property filters, lead the index
400
with the traversal endpoint key followed by the filtered column, and
401
interleave into the endpoint node table.
402
- For per-node Top-K queries (`ORDER BY e.{ts} DESC LIMIT k` from an anchored
403
node) on high-degree nodes, index `({src_id}, {ts} DESC)` with `STORING` so
404
Spanner pushes `LIMIT k` directly into the index scan and reads only `k`
405
index rows instead of sorting the full adjacency list:
406
407
```sql
408
-- Forward filter on (src_id, create_time)
409
CREATE INDEX PersonOwnAccountByTime
410
ON PersonOwnAccount (person_id, create_time), INTERLEAVE IN Person;
411
-- Per-node Top-K by create_time DESC
412
CREATE INDEX AccountTransferByTimeDesc
413
ON AccountTransferAccount (src_id, create_time DESC) STORING (amount),
414
INTERLEAVE IN Account;
415
```
416
417
- Never list the edge table's primary key columns in `STORING`; they are
418
already part of every index and Spanner rejects the DDL.
419
3. **Referential Integrity & TTL (`ROW DELETION POLICY`)**:
420
- Prevent dangling edges (edges pointing to deleted nodes) using `INTERLEAVE
421
IN PARENT {source_node_table} ON DELETE CASCADE` and `FOREIGN KEY ... ON
422
DELETE CASCADE` on the destination node.
423
- **Same-Node-Type Edge Exception**: When an edge connects two nodes of the
424
**same** table (e.g., `Account -> Account` in `AccountTransferAccount`),
425
Spanner does not allow combining `INTERLEAVE IN PARENT Account ON DELETE
426
CASCADE` with a second `ON DELETE CASCADE` foreign key to `Account`. If
427
symmetric cascading deletes are required when either endpoint is deleted,
428
make the edge table standalone (not interleaved) with two enforced
429
`FOREIGN KEY ... REFERENCES Account (id) ON DELETE CASCADE` constraints.
430
- When adding a `ROW DELETION POLICY (OLDER_THAN({timestamp_col}, INTERVAL
431
{n} DAY))` to a node table, ensure all attached edge tables either cascade
432
deletes (`ON DELETE CASCADE`) or use informational foreign keys (`NOT
433
ENFORCED`, which leaves dangling edges for the application to clean up),
434
because Spanner rejects node TTL policies if enforced non-cascading child
435
edges block expiration.
436
437
### Step 5: Validate Schema DDL & Tear Down Temporary Resources
438
439
Validate the generated DDL against the real Spanner engine whenever possible
440
before presenting it as final:
441
442
1. **Preferred — Validate on a User-Confirmed Spanner Instance**: Ask the user
443
whether they have a Spanner instance (for example, a development or test
444
instance) where you may create a temporary, empty database, and confirm the
445
instance and database name before creating anything (creating a database
446
can incur costs). Apply the complete schema (tables, indexes, and `CREATE
447
PROPERTY GRAPH`) to that empty database:
448
```bash
449
gcloud spanner databases create {temp_database_id} \
450
--instance={instance_id} --project={project_id} \
451
--ddl-file={schema_file}
452
```
453
Never apply unvalidated DDL to an existing database that contains data.
454
2. **Fallback — Local Spanner Emulator**: If no Spanner instance is available,
455
follow the official
456
[Spanner Emulator guide](https://docs.cloud.google.com/spanner/docs/emulator.md.txt)
457
to start or connect to the local emulator (if it isn't installed, ask the
458
user before installing it). Create an isolated `gcloud` configuration
459
(`gcloud config configurations create emulator --no-activate`) and pass
460
`--configuration=emulator` on every validation command so DDL never reaches a
461
real instance, then apply the schema with `gcloud spanner databases create
462
{database_id} --instance={instance_id} --ddl-file={schema_file}
463
--configuration=emulator`. Because the emulator doesn't reproduce every
464
engine-specific validation, tell the user that emulator validation is a
465
best-effort check and recommend re-validating on a real instance before
466
production use. If neither `gcloud` nor the emulator is available, verify
467
the DDL statically against the checklist below.
468
3. If the compiler reports errors (such as mismatched shared label properties,
469
invalid key arity in `SOURCE KEY` / `DESTINATION KEY`, or conflicting
470
`ON DELETE CASCADE` constraints on same-type nodes), fix the DDL and re-run
471
until validation succeeds.
472
4. **Clean Up Temporary Validation Resources**: Delete the temporary validation
473
database when finished (`gcloud spanner databases delete {temp_database_id}
474
--instance={instance_id} --quiet`, adding `--configuration=emulator` for the
475
emulator; also delete any temporary emulator instance with `gcloud spanner
476
instances delete {instance_id} --quiet --configuration=emulator`) so the
477
user doesn't incur ongoing storage charges.
478
5. Run through the **Schema Verification Checklist** below before returning the
479
final DDL.
480
481
## Schema Verification Checklist
482
483
- [ ] **No Monotonic Primary Keys & Compact Key Types**: Node and standalone
484
edge primary keys avoid sequential timestamps or auto-incrementing
485
integers as the first key part (prefer random/bit-reversed `INT64` or
486
native `UUID` over `STRING(36)`).
487
- [ ] **Edge Key Prefix & Co-Location**: Dedicated `M:N` edge tables use
488
`PRIMARY KEY ({src_key}, {dst_key}, ...)` and `INTERLEAVE IN PARENT
489
{source_node_table}`.
490
- [ ] **Interleaved Child Nodes Are Strict 1:N**: Node tables interleaved in
491
another node table (`INTERLEAVE IN PARENT`) represent strict `1:N`
492
containment; `M:N` relationships between node types use a dedicated edge
493
table instead.
494
- [ ] **Folded Pass-Through Node Types Are User-Confirmed**: Any 1:1
495
intermediate node type folded into an edge table (and therefore absent
496
from the graph schema) was explicitly confirmed with the user.
497
- [ ] **Cardinality-Safe Edge Folding**: Only `many-to-{0,1}` and `many-to-1`
498
edges are folded into source node tables via `Table AS Edge`; all `M:N`
499
edges remain in separate edge tables so node row counts (`COUNT(n)`) are
500
never inflated, and folded target-key columns use enforced foreign keys
501
without `ON DELETE CASCADE`.
502
- [ ] **Reverse Traversal Index Coverage**: Every edge traversed in reverse
503
(`<-[e]-`) or any direction (`-[e]-`) has a secondary index on
504
`({dst_key}, {src_key})` with `STORING (...)` (and `INTERLEAVE IN
505
{dest_node_table}` when key prefixes align).
506
- [ ] **Destination Join Elimination**: Edge tables define foreign keys on
507
`DESTINATION KEY` columns (enforced by default; `NOT ENFORCED` only for
508
hub nodes after the user accepts the dangling-edge risk).
509
- [ ] **Shared Label Uniformity**: Any `LABEL` shared across multiple tables
510
exposes identical property names and data types (using `CAST` where
511
needed).
512
- [ ] **Dangling Edge & TTL Safety**: `ON DELETE CASCADE` and `ROW DELETION
513
POLICY` rules are consistent across parent nodes and attached edges.
514
515
## Reference Guides
516
517
- [Edge Traversal & Indexing](references/edge-traversal-and-indexing.md):
518
Complete DDL patterns for forward interleaving, destination foreign keys,
519
reverse covering `STORING` indexes, property-filtering indexes, same-node-type
520
cascades, and TTL policies.
521
- [Topology & Edge Folding](references/topology-and-edge-folding.md): Decision
522
matrix for schematized vs. schemaless graphs, multi-table label alignment, 1:N
523
node hierarchy interleaving, 1:1 subtype consolidation, and cardinality-safe
524
`many-to-{0,1}` / `many-to-1` edge folding.
525
- [Official Spanner Graph Schema Design Best Practices](https://docs.cloud.google.com/spanner/docs/graph/best-practices-designing-schema.md.txt):
526
Google Cloud documentation for Spanner Graph physical schema design.
527
528
If you need product information that's not found in these references, use the
529
`search_documents` tool of the Developer Knowledge MCP server.
530