← Cloud · GCP← Cloud · GCP
Cloud · GCPCloud · GCP19 Th7, 2026Jul 19, 202613 phút đọc10 min read

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ómDịch vụMô hình dữ liệuTương đương AWS
Quan hệ (OLTP)Cloud SQLMySQL / PostgreSQL / SQL ServerRDS
Quan hệ (hiệu năng cao)AlloyDBTương thích PostgreSQLAurora (PostgreSQL)
Quan hệ (toàn cầu)Cloud SpannerSQL scale ngangLai Aurora / DynamoDB
DocumentFirestoreDocument (collection/doc)DynamoDB / DocumentDB
Wide-columnBigtableKey → hàng rộng, NoSQLDynamoDB / Keyspaces
Analytics (OLAP)BigQueryData warehouse dạng cộtRedshift / Athena
Cache in-memoryMemorystoreRedis / MemcachedElastiCache

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:

# 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ạnhSQL 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).

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.

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á:

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

MemorystoreRedis (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

Chọn database
  1. ?Truy vấn phân tích / data warehouse / dashboard trên dữ liệu khổng lồ?
    BigQueryOLAP serverless; partition + cluster
  2. ?Cần SQL quan hệ (join, transaction, schema)? Scale toàn cầu + ghi ngang + nhất quán mạnh?
    Cloud Spanner
  3. ?Cần SQL quan hệ? Vượt Postgres về hiệu năng, vẫn kiểu single-region?
    AlloyDB
  4. ?Cần SQL quan hệ? OLTP single-region tiêu chuẩn (MySQL/Postgres/SQLServer)?
    Cloud SQL
  5. ?Mô hình document, backend mobile/web, real-time, schema linh hoạt?
    Firestore
  6. ?NoSQL theo key khổng lồ, time-series/IoT, throughput ghi khổng lồ?
    Bigtable
  7. ?Chỉ cần một cache / session store / bảng xếp hạng?
    MemorystoreRedis

Đánh đổi giữa nhất quán và quy mô

Dịch vụNhất quánScale ghiLinh hoạt truy vấn
Cloud SQLMạnh (một primary)Một node (dọc)SQL đầy đủ
AlloyDBMạnh (một primary)Một node + read poolSQL đầy đủ
SpannerMạnh, externalNgang (thêm node)SQL (một số giới hạn)
FirestoreMạnh theo documentNgang (tự động)Hạn chế (có index)
BigtableMạnh theo hàngNgang (thêm node)Chỉ quét row-key
BigQueryKhông áp dụng (analytics)Không áp dụngSQL đầy đủ (OLAP)

Quan hệ vs document vs wide-column vs analytics

Best Practices

  1. 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ự.

  2. 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.

  3. 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.

  4. 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ở.

  5. 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.

  6. 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.

  7. 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.

  8. 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.

  9. 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.

  10. 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ẻ.

  11. Đặ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.

  12. 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.

  13. 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.

  14. 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ỉ.

  15. Đặ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.

  16. 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

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.

CategoryServiceData modelAWS equivalent
Relational (OLTP)Cloud SQLMySQL / PostgreSQL / SQL ServerRDS
Relational (high-perf)AlloyDBPostgreSQL-compatibleAurora (PostgreSQL)
Relational (global)Cloud SpannerHorizontally scalable SQLAurora / DynamoDB hybrid
DocumentFirestoreDocument (collections/docs)DynamoDB / DocumentDB
Wide-columnBigtableKey → wide rows, NoSQLDynamoDB / Keyspaces
Analytics (OLAP)BigQueryColumnar data warehouseRedshift / Athena
In-memory cacheMemorystoreRedis / MemcachedElastiCache

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:

# 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).

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.

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:

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

Choosing a database
  1. ?Analytical queries / data warehouse / dashboards over huge data?
    Yes
    BigQueryserverless OLAP; partition + cluster
  2. ?Need relational SQL (joins, transactions, schema)? Global scale + horizontal writes + strong consistency?
    Yes
    Cloud Spanner
  3. ?Need relational SQL? Outgrew Postgres on perf, still single-region-ish?
    Yes
    AlloyDB
  4. ?Need relational SQL? Standard single-region OLTP (MySQL/Postgres/SQLServer)?
    Yes
    Cloud SQL
  5. ?Document model, mobile/web backend, real-time, flexible schema?
    Yes
    Firestore
  6. ?Massive key-based NoSQL, time-series/IoT, huge write throughput?
    Yes
    Bigtable
  7. ?Just need a cache / session store / leaderboard?
    Yes
    MemorystoreRedis

Consistency and scale trade-offs

ServiceConsistencyWrite scalingQuery flexibility
Cloud SQLStrong (single primary)Single node (vertical)Full SQL
AlloyDBStrong (single primary)Single node + read poolFull SQL
SpannerStrong, externalHorizontal (add nodes)SQL (some limits)
FirestoreStrong per-documentHorizontal (auto)Limited (indexed)
BigtableStrong per-rowHorizontal (add nodes)Row-key scans only
BigQueryN/A (analytics)N/AFull SQL (OLAP)

Relational vs document vs wide-column vs analytics

Best Practices

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. 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.

  9. 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.

  10. 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.

  11. 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.

  12. 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.

  13. 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.

  14. 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.

  15. 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.

  16. 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