Skip to content

etcd vs Spanner Backend — GKE State Storage & Consistency Model

Tại Sao Backend Storage Quan Trọng

Kubernetes cluster state — tất cả Pods, Services, ConfigMaps, Secrets — phải lưu ở nơi bền vững. Backend storage không chỉ ảnh hưởng đến sẵn sàng, mà cả latency API requests, tính đúng đắn vòng lặp hoà hợp, và khả năng phục hồi thảm họa.

Lựa chọn backend sai → delays lan truyền, trạng thái không nhất quán, mất dữ liệu.


etcd — Kubernetes Default Backend

Tổng Quan Kiến Trúc

etcd là distributed key-value store dựa trên Raft consensus algorithm. Mỗi ghi phải được sao chép qua đa số (quorum) trước khi lưu.

etcd Cluster (3 nodes điển hình)
├─ Node 1 (Leader)
│  └─ Nhận ghi
│     └─ Broadcasts RPC append-entry
├─ Node 2 (Follower)
│  └─ Nhận append-entry
│     └─ Lưu vào disk
│     └─ Ack leader
└─ Node 3 (Follower)
   └─ Tương tự Node 2

Khi 2/3 nodes ack → Leader lưu

Đường Dẫn Nhất Quán Ghi

API Server:
   Yêu cầu ghi

   Xác thực/Uỷ quyền

   etcd.Put(key, value)

   Raft leader nhận ghi

   Raft log append + broadcast cho followers

   Chờ quorum acks

   Lưu vào state machine (persisted)

   Trả về success cho API Server

   API Server trả response cho client

Latency: điển hình 10-50ms per ghi (phụ thuộc mạng, disk I/O)

Đảm Bảo Nhất Quán Mạnh

etcd cung cấp nhất quán mạnh:

  • Ghi phải lưu quorum trước ack
  • Đọc từ leader luôn tươi
  • Đọc từ follower có thể cũ (cần cẩn thận)
bash
# GKE sử dụng etcd với nhất quán mạnh
# Tất cả Kubernetes API đọc từ etcd đảm bảo dữ liệu tươi

Giới Hạn của etcd

Giới HạnẢnh HưởngVí Dụ
Giới hạn kích thước key~1 MB per keyConfigMap/Secret lớn bị từ chối
Giới hạn kích thước value~1-2 GB tổngGiới hạn thực tế ~100k objects
Throughput ghi~1000s ghi/giâyWorkload churn cao bị throttle
Xử lý network partitionKhông sẵn sàng nếu thiểu sốSplit-brain prevention
Kích thước transaction~1-10k operationsBatch deletions có thể fail

etcd Backup & Recovery

GKE automatically manages etcd backups:

bash
# GKE automated backups
gcloud container backups describe <backup-id>

# Restore procedure
gcloud container backups restore <backup-id> \
  --cluster-name=my-cluster

Thời gian phục hồi: ~30 phút để restore snapshot + replay logs


Spanner Backend — Google's Distributed SQL

Tổng Quan Kiến Trúc

Spanner là globally-distributed SQL database với nhất quán mạnh (giống etcd) nhưng khả năng thêm:

Spanner Cluster (Google-quản lý)
├─ Regions (3+)
│  └─ Replicas
│     └─ Nhất quán mạnh qua TrueTime
├─ Sao chép tự động
├─ Failover multi-region
└─ ACID transactions

Write Consistency Path (Spanner)

API Server:
   Write request

   Spanner transaction begin

   Write to Spanner (using TrueTime-synchronized clocks)

   Spanner replicates across quorum in multiple regions

   Transaction committed

   Spanner returns success

   API Server returns response

Latency: điển hình 50-200ms (phụ thuộc region replicas) — chậm hơn etcd!

Ưu Điểm của Spanner

Ưu ĐiểmẢnh HưởngTrường Hợp Sử Dụng
Multi-region HAFailover tự độngRegional failures trong suốt
SQL queriesAudit, forensicsQuery state trực tiếp
Quy mô lớn hơn10M+ objectsClusters rất lớn
Built-in backupsPoint-in-time recoveryYêu cầu quy định
Semantics mạnh hơnACID transactionsThay đổi trạng thái phức tạp

Ma Trận Tradeoff etcd vs Spanner

Khía CạnhetcdSpanner
Latency10-50ms50-200ms
Throughput~1000s ghi/giây~100s ghi/giây (điển hình)
Quy mô~100k objects~10M objects
HA regionSingle regionMulti-region built-in
Backup complexityManual snapshotsBuilt-in, tự động
Query capabilityKey-value chỉFull SQL
Chi phíThấp hơnCao hơn
Đơn giản vận hànhNhiều toolsQuản lý bởi Google

GKE State Storage Choices

Standard Cluster (Default)

GKE Standard clusters mặc định etcd backend trong cấu hình 3-zone HA:

GKE Cluster (us-central1)
├─ Control Plane Zone 1
│  └─ etcd replica
├─ Control Plane Zone 2
│  └─ etcd replica
└─ Control Plane Zone 3
   └─ etcd replica

Tất cả replicas đồng bộ, quorum = 2/3

Autopilot Cluster (Optional)

Autopilot clusters có thể chọn giữa etcd hoặc Spanner khi tạo:

bash
# etcd backend (mặc định)
gcloud container clusters create my-autopilot \
  --enable-autopilot \
  --zone us-central1-a \
  --database-backend etcd

# Spanner backend (thay thế)
gcloud container clusters create my-autopilot \
  --enable-autopilot \
  --zone us-central1-a \
  --database-backend spanner

Lưu ý: Một khi chọn backend, không thể thay đổi mà không recreate cluster.


Consistency Model Details

Đảm Bảo Nhất Quán Mạnh (Cả Hai Backends)

Cả etcd lẫn Spanner đảm bảo:

  1. Atomicity ghi: Ghi hoặc thành công hoàn toàn hoặc thất bại hoàn toàn
  2. Tươi ghi: Đọc luôn thấy ghi committed mới nhất
  3. Thứ tự: Ghi được sắp xếp đúng
  4. Không divergence: Không version conflicts

Watch API — Event Streaming

Cả hai backends hỗ trợ watch API để streaming changes:

bash
# Watch tất cả Pods changes
kubectl get pods --watch

# Dưới nắp: API Server watches etcd/Spanner changes

Quan trọng: Watch không bỏ lỡ sự kiện, nhưng có delay:

  • etcd: biasanya <100ms
  • Spanner: biasanya <500ms

Tầng Cache API Server

Mặc dù backend có consistency, API Server có local cache cho performance:

┌─────────────────────────────┐
│  API Server                 │
│                             │
│ ┌─────────────────────────┐ │
│ │ Local Cache (in-memory) │ │
│ │ (objects API Server     │ │
│ │  gần đây truy cập)     │ │
│ └─────────────────────────┘ │
│   ↓                    ↑     │
│   └────Watch API ──────┘     │
│                             │
│ Cho ghi: luôn đi tới       │
│ backend (etcd/Spanner)      │
└─────────────────────────────┘

┌─────────────────────────────┐
│  etcd / Spanner             │
│  (persistent state)         │
└─────────────────────────────┘

Ảnh hưởng: Cached đọc có thể cũ nếu watch connection bị rơi.


Scaling Implications

Object Count Scaling

Countetcd ConcernSpanner Concern
100kMặc định, OKHoạt động, có thể quá
500kHợp lýFit tốt hơn
1M+Vấn đềFit tốt hơn

Write Rate Scaling

Req/GiâyetcdSpannerGiảm Nhẹ
100OKOK-
500OKOK-
1000+Stress pointTốt hơnClient-side batching
10000+Không thểKhóShard cluster

Cách khác điển hình cho high write rate: Setup multi-cluster với sharding.


Disaster Recovery

etcd Backup Strategy

GKE automated backups, tapi production pattern:

  1. Enable automated backups:
bash
gcloud container backups describe <backup>
# Shows: full snapshot + incremental backups
  1. Test recovery (critical!):
bash
# Create test cluster dari backup
gcloud container backups restore <backup> \
  --cluster-name=test-restore
  1. RPO/RTO typically:
  • RPO: 1 hour (backup frequency)
  • RTO: 30 minutes (restore time)

Spanner Advantages untuk DR

Spanner offers:

  • Point-in-time recovery: Recover ke specific timestamp
  • Automatic replication: Multi-region backup implicit
  • Built-in redundancy: Data loss casi impossible

Performance Tuning

etcd Performance Tuning (GKE)

Limited tuning surface, tapi dapat monitor:

bash
# Check etcd latency
kubectl get --raw /metrics | grep etcd_disk_backend_commit_duration

# Check etcd object count
kubectl get --raw /metrics | grep etcd_object_counts

Spanner Performance Tuning

Usually managed by Google, tapi bisa monitor:

bash
# Check Spanner latency
gcloud spanner operations list \
  --instance=<instance> \
  --database=<database>

Production Patterns

Pattern 1: Separate Metadata vs Data

Besar objek (ConfigMap dengan 10MB) masuk backend juga:

yaml
# ❌ BAD - Large ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
  name: large-config
data:
  data.txt: |
    [10 MB of data]  # Now in etcd/Spanner!

# ✅ GOOD - Store reference only
apiVersion: v1
kind: ConfigMap
metadata:
  name: config-ref
data:
  storage-url: gs://bucket/data.txt

Pattern 2: Object Count Management

Clusters dengan 500k+ objects biasanya lebih baik dengan:

  1. Shard into multiple clusters
  2. Archive old objects
  3. Implement cleanup policies
bash
# Monitor object count
kubectl get all -A --no-headers | wc -l

# Archive old completed jobs
kubectl delete jobs -A \
  --field-selector status.successful=1 \
  --older-than 7d

Migration Between Backends

GKE tidak support live migration between etcd ↔ Spanner. Options:

  1. Recreate cluster: Simple, downtime required
  2. Migrate data: Export/import workflow (complex)
  3. Multi-cluster: New cluster parallel, migrate workload

Reference Dokumentasi


Summary

  • etcd: Default Kubernetes backend, good balance latency/scale, <100k objects typical
  • Spanner: Google's distributed SQL, multi-region HA, better untuk large clusters
  • Both guarantee strong consistency, differences di scaling, DR, operational complexity
  • API Server caching layer adds complexity untuk understanding staleness
  • Backup/recovery strategy critical — test regularly
  • Shard clusters khi single cluster mencapai state limits