DatabasesDatabases
Part of the Cloud knowledge base — GCP deep dive. Complements DevOps Roadmap.
Tổng quan
Google Cloud có một database cho mọi mô hình dữ liệu. Chọn tốt nghĩa là khớp hình dạng dữ liệu, nhu cầu về tính nhất quán, quy mô, và pattern truy vấn của bạn với đúng engine — dùng một DB quan hệ cho analytics hay một DB document cho các join đều là những sai lầm tốn kém.
| Nhóm | Dịch vụ | Mô hình dữ liệu | Tương đương AWS |
|---|---|---|---|
| Quan hệ (OLTP) | Cloud SQL | MySQL / PostgreSQL / SQL Server | RDS |
| Quan hệ (hiệu năng cao) | AlloyDB | Tương thích PostgreSQL | Aurora (PostgreSQL) |
| Quan hệ (toàn cầu) | Cloud Spanner | SQL scale ngang | Lai Aurora / DynamoDB |
| Document | Firestore | Document (collection/doc) | DynamoDB / DocumentDB |
| Wide-column | Bigtable | Key → hàng rộng, NoSQL | DynamoDB / Keyspaces |
| Analytics (OLAP) | BigQuery | Data warehouse dạng cột | Redshift / Athena |
| Cache in-memory | Memorystore | Redis / Memcached | ElastiCache |
Phân chia bậc nhất: hệ thống giao dịch (OLTP) phục vụ nhiều lần đọc/ghi nhỏ với độ trễ thấp; hệ thống phân tích (OLAP) quét khối lượng khổng lồ để tổng hợp. Đừng chạy analytics trên database OLTP của bạn.
Kiến thức nền tảng
Cloud SQL
Cloud SQL là MySQL, PostgreSQL, và SQL Server được quản lý — Google lo việc provisioning, patching, backup, replication, và failover, trong khi bạn có một SQL engine tiêu chuẩn.
Các khả năng chính:
- High Availability (HA) — cấu hình regional giữ một standby đồng bộ ở zone khác; khi có sự cố nó tự động failover. Xấp xỉ gấp đôi chi phí nhưng cho một SLA mạnh.
- Read replicas — các replica bất đồng bộ (cùng hoặc cross-region) để chia tải đọc. Chúng không dùng cho HA (do lag bất đồng bộ) nhưng scale đọc và cho phép đọc gần người dùng.
- Backup tự động + point-in-time recovery (PITR) — backup hàng ngày cộng binary/WAL log cho phép khôi phục về một thời điểm cụ thể.
- Kết nối — private IP (VPC), public IP với authorized network, hoặc Cloud SQL Auth Proxy / connector để truy cập an toàn dựa trên IAM mà không cần mở network.
# Tạo một instance PostgreSQL HA với backup tự động
gcloud sql instances create orders-db \
--database-version=POSTGRES_16 \
--tier=db-custom-4-16384 \
--region=us-central1 \
--availability-type=REGIONAL \
--storage-auto-increase \
--backup-start-time=03:00 \
--enable-point-in-time-recovery
# Thêm một read replica
gcloud sql instances create orders-db-replica \
--master-instance-name=orders-db \
--region=us-east1
Khi nào dùng: mặc định cho các workload quan hệ truyền thống dưới ngưỡng scale một region (tới hàng chục TB, single-writer). Cạm bẫy: một primary duy nhất là nút thắt ghi — Cloud SQL scale đọc, không scale ghi, vượt quá một node.
AlloyDB (tóm tắt)
AlloyDB là một engine tương thích PostgreSQL tách rời compute và storage, thêm một accelerator dạng cột in-memory cho các truy vấn phân tích, và cho throughput cao hơn nhiều cùng đọc nhanh hơn so với Cloud SQL Postgres tiêu chuẩn. Dùng nó khi bạn đã vượt quá Cloud SQL Postgres về hiệu năng nhưng muốn giữ tương thích PostgreSQL và single-region (hoặc với replica cross-region). Đây là đối thủ Aurora của Google.
Cloud Spanner
Cloud Spanner là một database quan hệ scale ngang, phân tán toàn cầu cung cấp tính nhất quán ngoài (external consistency) mạnh và SQL quan hệ với schema và secondary index — không cần quản lý sharding. Nó scale ghi và đọc bằng cách thêm node và có thể trải qua các region/châu lục trong khi vẫn nhất quán (nhờ TrueTime).
- Khi nào dùng: bạn cần ngữ nghĩa quan hệ và scale ngang gần như không giới hạn, dấu chân toàn cầu, tính sẵn sàng 99.999%, và không thể chấp nhận ngưỡng single-writer của Cloud SQL (vd tồn kho toàn cầu, sổ cái tài chính, bảng xếp hạng game).
- Cạm bẫy: chi phí và kỷ luật thiết kế — bạn phải chọn primary key tốt để tránh hotspot (tránh key tăng đơn điệu). Quá mức cần thiết cho các ứng dụng nhỏ single-region.
Firestore / Datastore
Firestore là một document database serverless, tự động scale (các collection chứa document, kiểu JSON). Nó cung cấp real-time listener, đồng bộ offline cho mobile/web, và tính nhất quán mạnh. Datastore là phiên bản tiền nhiệm; Firestore ở chế độ Datastore là kế thừa cho các workload server.
// Mô hình dữ liệu Firestore — một collection "users" với subcollection lồng nhau
// users/{userId}
{
displayName: "Ada",
email: "ada@example.com",
createdAt: Timestamp,
plan: "pro"
}
// users/{userId}/orders/{orderId} (subcollection)
{
total: 42.50,
status: "shipped",
items: [{ sku: "A1", qty: 2 }]
}
// Truy vấn: các đơn đã giao của người dùng này, mới nhất trước
const snap = await db.collection(`users/${uid}/orders`)
.where("status", "==", "shipped")
.orderBy("createdAt", "desc")
.limit(20)
.get();
Khi nào dùng: backend cho ứng dụng mobile/web, profile người dùng, ứng dụng real-time, schema thay đổi nhanh. Cạm bẫy: truy vấn phải được hỗ trợ bởi index và không thể join tùy ý hay tổng hợp qua các collection — hãy mô hình hóa dữ liệu quanh pattern đọc, và denormalize.
Bigtable
Cloud Bigtable là một database wide-column NoSQL cho các workload khổng lồ, độ trễ thấp, throughput cao (petabyte, hàng triệu ops/giây ở độ trễ mili-giây một chữ số). Đây là engine phía sau Search, Maps, và Analytics, và nói giao thức HBase API.
- Dữ liệu là một map khổng lồ được sắp xếp, khóa bởi một row key duy nhất; thiết kế row key để khớp pattern truy vấn (truy vấn là quét dải row-key, không phải SQL tùy ý).
- Khi nào dùng: time-series, telemetry IoT, ad-tech, tick tài chính, cá nhân hóa — lượng ghi khổng lồ và tra cứu theo key.
- Cạm bẫy: không có secondary index, không join, không transaction qua các hàng (chỉ atomic một hàng). Thiết kế row-key kém tạo hotspot.
BigQuery
BigQuery là một data warehouse serverless dạng cột cho analytics. Bạn load hoặc stream dữ liệu và chạy SQL trên terabyte/petabyte mà không quản lý hạ tầng — storage và compute tách rời và scale độc lập.
Các mô hình giá:
- On-demand — trả theo mỗi TB được quét bởi từng truy vấn.
- Capacity (slot) — đặt trước compute (slot) cho các workload có thể dự đoán, khối lượng lớn.
Partitioning và clustering là các đòn bẩy chi phí/hiệu năng chính: partitioning (thường theo ngày) cắt bỏ toàn bộ partition để truy vấn quét ít dữ liệu hơn; clustering sắp xếp dữ liệu trong partition theo các cột đã chọn để giảm thêm số byte được quét.
-- Tạo một bảng partitioned + clustered
CREATE TABLE analytics.events
(
event_time TIMESTAMP,
user_id STRING,
event_type STRING,
country STRING,
revenue NUMERIC
)
PARTITION BY DATE(event_time)
CLUSTER BY event_type, country;
-- Một truy vấn chỉ quét partition của một ngày và các cột clustered
SELECT country, COUNT(*) AS purchases, SUM(revenue) AS total
FROM analytics.events
WHERE DATE(event_time) = '2026-07-17' -- cắt xuống một partition
AND event_type = 'purchase' -- dùng clustering
GROUP BY country
ORDER BY total DESC;
Khi nào dùng: dashboard, analytics ad-hoc, ELT, ML trên dữ liệu có cấu trúc (BigQuery ML). Cạm bẫy: SELECT * và quét toàn bộ không partition là thứ làm phình hóa đơn on-demand — luôn lọc theo cột partition và chỉ chọn các cột cần thiết.
Memorystore
Memorystore là Redis (và Memcached) được quản lý cho cache in-memory, session store, bảng xếp hạng, và pub/sub. Nó cung cấp HA (Redis với replica + failover tự động), scaling, và patching. Dùng nó trước Cloud SQL/Spanner/Firestore để hấp thụ các lần đọc nóng và cắt độ trễ xuống dưới mili-giây.
Khái niệm chính
Chọn một database
- ?Truy vấn phân tích / data warehouse / dashboard trên dữ liệu khổng lồ?CóBigQueryOLAP serverless; partition + cluster
- ?Cần SQL quan hệ (join, transaction, schema)? Scale toàn cầu + ghi ngang + nhất quán mạnh?CóCloud Spanner
- ?Cần SQL quan hệ? Vượt Postgres về hiệu năng, vẫn kiểu single-region?CóAlloyDB
- ?Cần SQL quan hệ? OLTP single-region tiêu chuẩn (MySQL/Postgres/SQLServer)?CóCloud SQL
- ?Mô hình document, backend mobile/web, real-time, schema linh hoạt?CóFirestore
- ?NoSQL theo key khổng lồ, time-series/IoT, throughput ghi khổng lồ?CóBigtable
- ?Chỉ cần một cache / session store / bảng xếp hạng?CóMemorystoreRedis
Đánh đổi giữa nhất quán và quy mô
| Dịch vụ | Nhất quán | Scale ghi | Linh hoạt truy vấn |
|---|---|---|---|
| Cloud SQL | Mạnh (một primary) | Một node (dọc) | SQL đầy đủ |
| AlloyDB | Mạnh (một primary) | Một node + read pool | SQL đầy đủ |
| Spanner | Mạnh, external | Ngang (thêm node) | SQL (một số giới hạn) |
| Firestore | Mạnh theo document | Ngang (tự động) | Hạn chế (có index) |
| Bigtable | Mạnh theo hàng | Ngang (thêm node) | Chỉ quét row-key |
| BigQuery | Không áp dụng (analytics) | Không áp dụng | SQL đầy đủ (OLAP) |
Quan hệ vs document vs wide-column vs analytics
- Quan hệ — dữ liệu chuẩn hóa với join, transaction, và schema chặt chẽ. Tốt nhất khi tính toàn vẹn và truy vấn phức tạp quan trọng (đơn hàng, thanh toán, tồn kho).
- Document — các bản ghi tự chứa có hình dạng như object ứng dụng của bạn; tuyệt cho dữ liệu linh hoạt/lồng nhau và truy cập đọc-theo-key.
- Wide-column — một kho key→hàng khổng lồ được sắp xếp; vô địch cho quy mô lớn và truy cập theo key nhưng không có join.
- Analytics (dạng cột) — tối ưu cho quét và tổng hợp hàng tỷ hàng; tệ cho OLTP mức hàng.
Best Practices
-
Dùng Cloud SQL HA (regional) cho production. Lý do: một standby đồng bộ ở zone khác với failover tự động là khác biệt giữa một cú chớp và một sự cố; chi phí thêm mua được một SLA thực sự.
-
Chia tải đọc sang replica, nhưng đừng bao giờ coi chúng là HA. Lý do: replica bất đồng bộ scale tải đọc và cho phép đọc gần người dùng, nhưng replication lag nghĩa là chúng không thể đảm bảo mất dữ liệu bằng không khi failover.
-
Bật backup tự động và PITR, và test khôi phục. Lý do: backup bạn chưa từng khôi phục là một hy vọng, không phải một kế hoạch; PITR giới hạn mất dữ liệu xuống vài phút.
-
Kết nối qua private IP và Cloud SQL Auth Proxy / connector. Lý do: giữ database tránh xa internet công cộng và dùng credential IAM ngắn hạn thay vì mật khẩu tĩnh trên các port mở.
-
Chọn Spanner chỉ khi bạn thực sự cần scale toàn cầu + nhất quán mạnh. Lý do: nó loại bỏ nỗi đau sharding ở quy mô thực, nhưng tốn kém và quá mức cần thiết cho các ứng dụng single-region mà Cloud SQL xử lý tốt.
-
Thiết kế key của Spanner/Bigtable để tránh hotspot. Lý do: key tăng đơn điệu (timestamp, ID tuần tự) dồn mọi lần ghi vào một server; dùng key hash/đảo/prefix để trải tải.
-
Partition và cluster các bảng BigQuery. Lý do: cắt partition và clustering giảm số byte được quét đi nhiều bậc — động lực chính của cả chi phí và tốc độ truy vấn.
-
Không bao giờ
SELECT *trong BigQuery; lọc theo cột partition. Lý do: lưu trữ dạng cột nghĩa là bạn trả tiền cho các cột và partition được quét; chỉ chọn cái cần và cắt partition trực tiếp giảm hóa đơn. -
Dùng capacity (slot) reservation của BigQuery cho các workload nặng ổn định. Lý do: analytics có thể dự đoán, khối lượng lớn rẻ hơn và ổn định hơn trên slot đặt trước so với giá on-demand theo TB.
-
Mô hình hóa Firestore quanh pattern đọc và denormalize. Lý do: Firestore không thể join hay tổng hợp qua các collection; cấu trúc document/subcollection theo truy vấn của bạn (và nhân bản dữ liệu) là cách giữ đọc nhanh và rẻ.
-
Đặt Memorystore trước các lần đọc nóng. Lý do: cache các truy vấn thường xuyên, tốn kém trong Redis cắt độ trễ xuống dưới mili-giây và giảm tải database chính, cải thiện cả chi phí và tính bền vững.
-
Chọn đúng engine, đừng ép một cái làm mọi thứ. Lý do: chạy analytics trên Cloud SQL hay join trên Bigtable là chống lại công cụ; khớp mô hình dữ liệu với workload tránh việc re-platform đau đớn về sau.
-
Right-size Cloud SQL và bật storage auto-increase. Lý do: tier over-provision lãng phí tiền trong khi storage under-provision gây sự cố; auto-increase ngăn sự cố đầy đĩa.
-
Dùng CMEK và ép mã hóa/TLS khi truyền cho dữ liệu bị quản chế. Lý do: key do khách hàng quản lý cộng kết nối SSL bắt buộc thỏa mãn compliance và kiềm chế bán kính ảnh hưởng của một credential rò rỉ.
-
Đặt maintenance window và theo dõi chúng trong monitoring. Lý do: kiểm soát thời điểm restart liên quan tới patch để chúng rơi vào khung giờ ít lưu lượng thay vì bất ngờ vào giờ cao điểm.
-
Theo dõi replication lag, truy vấn chậm, và số lượng kết nối. Lý do: đây là các metric cảnh báo sớm cho rắc rối database; cạn kiệt kết nối và lag gây ra hầu hết sự cố managed-DB.
Tài liệu tham khảo
- Cloud SQL documentation
- Cloud SQL high availability
- Cloud SQL read replicas
- Cloud SQL Auth Proxy
- AlloyDB for PostgreSQL
- Cloud Spanner documentation
- Spanner schema and key design
- Firestore documentation
- Firestore data model
- Cloud Bigtable documentation
- Bigtable schema design
- BigQuery documentation
- BigQuery partitioned tables
- BigQuery clustered tables
- Memorystore for Redis
- Choosing a database (Google Cloud)
Part of the Cloud knowledge base — GCP deep dive. Complements DevOps Roadmap.
Overview
Google Cloud has a database for every data model. Choosing well means matching your data shape, consistency needs, scale, and query patterns to the right engine — using a relational DB for analytics or a document DB for complex joins are both expensive mistakes.
| Category | Service | Data model | AWS equivalent |
|---|---|---|---|
| Relational (OLTP) | Cloud SQL | MySQL / PostgreSQL / SQL Server | RDS |
| Relational (high-perf) | AlloyDB | PostgreSQL-compatible | Aurora (PostgreSQL) |
| Relational (global) | Cloud Spanner | Horizontally scalable SQL | Aurora / DynamoDB hybrid |
| Document | Firestore | Document (collections/docs) | DynamoDB / DocumentDB |
| Wide-column | Bigtable | Key → wide rows, NoSQL | DynamoDB / Keyspaces |
| Analytics (OLAP) | BigQuery | Columnar data warehouse | Redshift / Athena |
| In-memory cache | Memorystore | Redis / Memcached | ElastiCache |
A first-order split: transactional (OLTP) systems serve many small reads/writes with low latency; analytical (OLAP) systems scan huge volumes for aggregation. Don’t run analytics on your OLTP database.
Fundamentals
Cloud SQL
Cloud SQL is managed MySQL, PostgreSQL, and SQL Server — Google handles provisioning, patching, backups, replication, and failover, while you get a standard SQL engine.
Key capabilities:
- High Availability (HA) — a regional configuration keeps a synchronous standby in another zone; on failure it automatically fails over. Roughly doubles cost but gives a strong SLA.
- Read replicas — asynchronous replicas (same or cross-region) to offload read traffic. They are not for HA (async lag) but scale reads and enable near-you reads.
- Automated backups + point-in-time recovery (PITR) — daily backups plus binary/WAL logs let you restore to a specific moment.
- Connectivity — private IP (VPC), public IP with authorized networks, or the Cloud SQL Auth Proxy / connectors for secure IAM-based access without opening the network.
# Create a HA PostgreSQL instance with automated backups
gcloud sql instances create orders-db \
--database-version=POSTGRES_16 \
--tier=db-custom-4-16384 \
--region=us-central1 \
--availability-type=REGIONAL \
--storage-auto-increase \
--backup-start-time=03:00 \
--enable-point-in-time-recovery
# Add a read replica
gcloud sql instances create orders-db-replica \
--master-instance-name=orders-db \
--region=us-east1
When to use: the default for traditional relational workloads under a single-region scale ceiling (up to tens of TB, single-writer). Pitfall: a single primary is the write bottleneck — Cloud SQL scales reads, not writes, beyond one node.
AlloyDB (brief)
AlloyDB is a PostgreSQL-compatible engine that separates compute and storage, adds a columnar in-memory accelerator for analytical queries, and offers much higher throughput and faster reads than standard Cloud SQL Postgres. Use it when you have outgrown Cloud SQL Postgres on performance but want to stay PostgreSQL-compatible and single-region (or with cross-region replicas). It is Google’s Aurora competitor.
Cloud Spanner
Cloud Spanner is a horizontally scalable, globally distributed relational database that provides strong external consistency and relational SQL with schema and secondary indexes — no sharding to manage. It scales writes and reads by adding nodes and can span regions/continents while staying consistent (backed by TrueTime).
- Use when: you need relational semantics and near-unlimited horizontal scale, global footprint, 99.999% availability, and can’t accept the single-writer ceiling of Cloud SQL (e.g. global inventory, financial ledgers, gaming leaderboards).
- Pitfall: cost and design discipline — you must choose good primary keys to avoid hotspots (avoid monotonically increasing keys). Overkill for small single-region apps.
Firestore / Datastore
Firestore is a serverless, autoscaling document database (collections of documents, JSON-like). It offers real-time listeners, offline sync for mobile/web, and strong consistency. Datastore is its predecessor; Firestore in Datastore mode is the successor for server workloads.
// Firestore data model — a "users" collection with nested subcollection
// users/{userId}
{
displayName: "Ada",
email: "ada@example.com",
createdAt: Timestamp,
plan: "pro"
}
// users/{userId}/orders/{orderId} (subcollection)
{
total: 42.50,
status: "shipped",
items: [{ sku: "A1", qty: 2 }]
}
// Query: this user's shipped orders, newest first
const snap = await db.collection(`users/${uid}/orders`)
.where("status", "==", "shipped")
.orderBy("createdAt", "desc")
.limit(20)
.get();
When to use: mobile/web app backends, user profiles, real-time apps, rapidly evolving schemas. Pitfall: queries must be backed by indexes and cannot do arbitrary joins or aggregations across collections — model your data around read patterns, and denormalize.
Bigtable
Cloud Bigtable is a wide-column NoSQL database for massive, low-latency, high-throughput workloads (petabytes, millions of ops/sec at single-digit-ms latency). It’s the engine behind Search, Maps, and Analytics, and speaks the HBase API.
- Data is a giant sorted map keyed by a single row key; design the row key to match query patterns (queries are row-key range scans, not arbitrary SQL).
- Use when: time-series, IoT telemetry, ad-tech, financial ticks, personalization — huge write volume and key-based lookups.
- Pitfall: no secondary indexes, no joins, no transactions across rows (single-row atomicity only). Poor row-key design creates hotspots.
BigQuery
BigQuery is a serverless, columnar data warehouse for analytics. You load or stream data and run SQL over terabytes/petabytes without managing infrastructure — storage and compute are separate and scale independently.
Pricing models:
- On-demand — pay per TB scanned by each query.
- Capacity (slots) — reserve compute (slots) for predictable, high-volume workloads.
Partitioning and clustering are the key cost/perf levers: partitioning (usually by date) prunes whole partitions so a query scans less data; clustering sorts data within partitions by chosen columns to further reduce scanned bytes.
-- Create a partitioned + clustered table
CREATE TABLE analytics.events
(
event_time TIMESTAMP,
user_id STRING,
event_type STRING,
country STRING,
revenue NUMERIC
)
PARTITION BY DATE(event_time)
CLUSTER BY event_type, country;
-- A query that only scans one day's partition and the clustered columns
SELECT country, COUNT(*) AS purchases, SUM(revenue) AS total
FROM analytics.events
WHERE DATE(event_time) = '2026-07-17' -- prunes to one partition
AND event_type = 'purchase' -- uses clustering
GROUP BY country
ORDER BY total DESC;
When to use: dashboards, ad-hoc analytics, ELT, ML on structured data (BigQuery ML). Pitfall: SELECT * and unpartitioned full scans are what run up on-demand bills — always filter on the partition column and select only needed columns.
Memorystore
Memorystore is managed Redis (and Memcached) for in-memory caching, session stores, leaderboards, and pub/sub. It provides HA (Redis with replica + automatic failover), scaling, and patching. Use it in front of Cloud SQL/Spanner/Firestore to absorb hot reads and cut latency to sub-millisecond.
Key Concepts
Choosing a database
- ?Analytical queries / data warehouse / dashboards over huge data?YesBigQueryserverless OLAP; partition + cluster
- ?Need relational SQL (joins, transactions, schema)? Global scale + horizontal writes + strong consistency?YesCloud Spanner
- ?Need relational SQL? Outgrew Postgres on perf, still single-region-ish?YesAlloyDB
- ?Need relational SQL? Standard single-region OLTP (MySQL/Postgres/SQLServer)?YesCloud SQL
- ?Document model, mobile/web backend, real-time, flexible schema?YesFirestore
- ?Massive key-based NoSQL, time-series/IoT, huge write throughput?YesBigtable
- ?Just need a cache / session store / leaderboard?YesMemorystoreRedis
Consistency and scale trade-offs
| Service | Consistency | Write scaling | Query flexibility |
|---|---|---|---|
| Cloud SQL | Strong (single primary) | Single node (vertical) | Full SQL |
| AlloyDB | Strong (single primary) | Single node + read pool | Full SQL |
| Spanner | Strong, external | Horizontal (add nodes) | SQL (some limits) |
| Firestore | Strong per-document | Horizontal (auto) | Limited (indexed) |
| Bigtable | Strong per-row | Horizontal (add nodes) | Row-key scans only |
| BigQuery | N/A (analytics) | N/A | Full SQL (OLAP) |
Relational vs document vs wide-column vs analytics
- Relational — normalized data with joins, transactions, and strict schema. Best when integrity and complex queries matter (orders, payments, inventory).
- Document — self-contained records shaped like your app objects; great for flexible/nested data and read-by-key access.
- Wide-column — a giant sorted key→row store; unbeatable for massive scale and key-based access but no joins.
- Analytics (columnar) — optimized for scanning and aggregating billions of rows; terrible for row-level OLTP.
Best Practices
-
Use HA (regional) Cloud SQL for production. Rationale: a synchronous standby in another zone with automatic failover is the difference between a blip and an outage; the extra cost buys a real SLA.
-
Offload reads to replicas, but never treat them as HA. Rationale: async replicas scale read traffic and enable near-user reads, but replication lag means they can’t guarantee zero data loss on failover.
-
Enable automated backups and PITR, and test restores. Rationale: backups you’ve never restored are a hope, not a plan; PITR limits data loss to minutes.
-
Connect via private IP and the Cloud SQL Auth Proxy / connectors. Rationale: keeps the database off the public internet and uses short-lived IAM credentials instead of static passwords on open ports.
-
Choose Spanner only when you truly need global scale + strong consistency. Rationale: it removes sharding pain at real scale, but is costly and overkill for single-region apps that Cloud SQL handles fine.
-
Design Spanner/Bigtable keys to avoid hotspots. Rationale: monotonically increasing keys (timestamps, sequential IDs) funnel all writes to one server; hash/reverse/prefix keys to spread load.
-
Partition and cluster BigQuery tables. Rationale: partition pruning and clustering cut scanned bytes by orders of magnitude — the primary driver of both query cost and speed.
-
Never
SELECT *in BigQuery; filter on the partition column. Rationale: columnar storage means you pay for columns and partitions scanned; selecting only what you need and pruning partitions directly reduces the bill. -
Use BigQuery capacity (slot) reservations for steady heavy workloads. Rationale: predictable, high-volume analytics is cheaper and more stable on reserved slots than per-TB on-demand pricing.
-
Model Firestore around read patterns and denormalize. Rationale: Firestore can’t join or aggregate across collections; structuring documents/subcollections for your queries (and duplicating data) is how you keep reads fast and cheap.
-
Put Memorystore in front of hot reads. Rationale: caching frequent, expensive queries in Redis cuts latency to sub-millisecond and offloads the primary database, improving both cost and resilience.
-
Pick the right engine, don’t force one to do everything. Rationale: running analytics on Cloud SQL or joins on Bigtable fights the tool; matching data model to workload avoids painful re-platforming later.
-
Right-size Cloud SQL and enable storage auto-increase. Rationale: over-provisioned tiers waste money while under-provisioned storage causes outages; auto-increase prevents disk-full incidents.
-
Use CMEK and enforce encryption/TLS in transit for regulated data. Rationale: customer-managed keys plus enforced SSL connections satisfy compliance and contain the blast radius of a leaked credential.
-
Set maintenance windows and read them in monitoring. Rationale: control when patch-related restarts happen so they land in low-traffic windows rather than surprising you at peak.
-
Watch replication lag, slow queries, and connection counts. Rationale: these are the early-warning metrics for database trouble; connection exhaustion and lag cause most managed-DB incidents.
References
- Cloud SQL documentation
- Cloud SQL high availability
- Cloud SQL read replicas
- Cloud SQL Auth Proxy
- AlloyDB for PostgreSQL
- Cloud Spanner documentation
- Spanner schema and key design
- Firestore documentation
- Firestore data model
- Cloud Bigtable documentation
- Bigtable schema design
- BigQuery documentation
- BigQuery partitioned tables
- BigQuery clustered tables
- Memorystore for Redis
- Choosing a database (Google Cloud)