هر Pod، هر Service، هر Secret، هر Deployment — همه در یک جا ذخیره میشوند:
/registry/pods/default/nginx-abc123
/registry/services/specs/default/kubernetesetcd همان «یک جا» است.
وقتی kubectl apply -f deployment.yaml میزنید، API server state را در etcd مینویسد. Scheduler و controllerها از همان state reconcile میکنند. etcd down = control plane مرده — حتی اگر هزار node worker سالم باشند.
etcd تعریف رسمی:
A distributed, reliable key-value store for the most critical data of a distributed system.
یعنی strongly consistent، highly available، Raft-backed — برای دادهای که split-brain نباید داشته باشد.
CNCF Graduated. Kubernetes، CoreDNS، Rook، M3 — همه به etcd یا الگوی آن وابستهاند.
مشکل consistency در سیستم توزیعشده
بدون consensus:
Node A: value=1
Node B: value=2
→ split-brain، stale read، data loss
با Raft (etcd):
Leader → replicate → quorum ack → commit
→ همه nodeها یک truth| معیار | Redis Cluster | Consul KV | ZooKeeper | etcd |
|---|---|---|---|---|
| Consistency | eventual (mode-dependent) | strong | strong | linearizable |
| Algorithm | custom | Raft | ZAB | Raft |
| K8s native | ❌ | optional | legacy | ✅ built-in |
| Watch API | Pub/Sub | yes | yes | ✅ efficient |
| HTTP/gRPC | RESP | HTTP+RPC | custom | gRPC v3 |
| CNCF | — | — | — | ✅ Graduated |
etcd برای control plane state طراحی شده — نه cache session یا message queue.
etcd چیست؟
etcd distributed key-value store است که:
- Strongly consistent — هر write موفق بلافاصله برای read بعدی visible
- Highly available — minority failure تحمل میشود
- Raft consensus — leader election + log replication
- Watch — client روی key/directory change subscribe میکند
- Hierarchical keys — مثل filesystem:
/foo/bar/baz - TTL — key expiration اختیاری
- gRPC API v3 —
etcdctlو client libraries
Repo: github.com/etcd-io/etcd
License: Apache 2.0
Versions: v3.8، v3.7، v3.6 (stable docs)، v3.5 (widely deployed)
Benchmark: هزاران write/s per instance
تاریخچه
| تاریخ | رویداد |
|---|---|
| ۲۰۱۳ | CoreOS team — برای Container Linux coordination |
| ۲۰۱۵ | Kubernetes adoption — backing store رسمی |
| ۲۰۱۸ | CNCF Incubating |
| ۲۰۱۹+ | CNCF Graduated |
| v3 | gRPC، MVCC، transaction — v2 deprecated |
| ongoing | v3.6+ — etcdutl برای restore، stream watch |
سازندگان: CoreOS (Red Hat) — همان تیم CoreDNS و Container Linux.
معماری داخلی
Client (API server / etcdctl)
↓ gRPC
etcd member
├── Raft module (leader election, log replication)
├── WAL (Write-Ahead Log) — durability قبل از apply
├── BoltDB — persistent KV store (bbolt)
└── MVCC — revision-based versioningRaft consensus
Cluster (N members):
1 Leader — همه writes از leader
N-1 Followers — replicate log
Quorum = majority = (N/2)+1
3 members → tolerate 1 failure
5 members → tolerate 2 failures
7 members → tolerate 3 (rarely needed)Leader election: heartbeat timeout → election → candidate با majority votes → leader جدید.
Write path:
- Client → Leader
- Leader append به Raft log
- Replicate به followers
- Quorum ack
- Commit + apply به state machine
- Response به client
قانون طلایی: تعداد member فرد — ۳ یا ۵ در production. ۴ member هزینه بیشتر، fault tolerance مثل ۳.
WAL (Write-Ahead Log)
هر mutation قبل از apply به BoltDB در WAL fsync میشود. Disk latency حیاتی است — WAL fsync p99 بالای ۱۰ms میتواند heartbeat timeout و leader election ناخواسته trigger کند.
MVCC
هر write revision جدید میسازد — read میتواند revision خاص یا latest باشد. Kubernetes informers از watch + revision برای cache sync استفاده میکنند.
BoltDB
Embedded key-value engine — snapshot + defrag برای maintenance.
API و etcdctl
Quickstart
# single-node dev
etcd
# another terminal
etcdctl put greeting "Hello, etcd"
etcdctl get greeting
# greeting
# Hello, etcdعملیات رایج v3
export ETCDCTL_API=3
# CRUD
etcdctl put /myapp/config '{"replicas":3}'
etcdctl get /myapp/config
etcdctl get /myapp/ --prefix
etcdctl del /myapp/config
# watch
etcdctl watch /myapp/ --prefix
# lease + TTL
etcdctl lease grant 60
etcdctl put /session/token "abc" --lease=<lease-id>
# transaction
etcdctl txn --compare='version("/key")=0' \
--then='put /key created' \
--else='get /key'
# cluster health
etcdctl endpoint health
etcdctl endpoint status -w table
etcdctl member listHTTP (curl)
curl -L http://localhost:2379/v2/keys/foo # v2 legacy
# v3 via gRPC — etcdctl preferredetcd در Kubernetes
etcd منبع حقیقت (single source of truth) cluster است.
kubectl → API server → etcd
Scheduler ← watch ← API server ← etcd
Controller Manager ← watch ← API server ← etcdفقط API server مستقیم با etcd صحبت میکند — scheduler، kubelet، controller هرگز مستقیم write نمیکنند.
چه چیزی در etcd ذخیره میشود؟
- Pods، Deployments، StatefulSets، DaemonSets
- Services، Endpoints، Ingress
- ConfigMaps، Secrets
- Namespaces، RBAC (Roles، Bindings)
- Custom Resources (CRD instances)
- Lease، coordination data
- Cluster metadata
Deployment patterns
| Pattern | توضیح |
|---|---|
| Stacked (kubeadm default) | etcd static Pod روی control plane node |
| External etcd cluster | etcd جدا — --etcd-servers=IP1:2379,... |
| Managed | EKS/GKE/AKS — etcd managed توسط cloud |
# kubeadm stacked
kubectl get pods -n kube-system -l component=etcd
# API server flag
--etcd-servers=https://127.0.0.1:2379
--etcd-cafile=...
--etcd-certfile=...
--etcd-keyfile=...Watch و informers
Kubernetes controllers با watch API etcd (via API server) تغییرات را stream میکنند. وقتی Pod create/delete میشود، informer cache update → reconcile loop.
این coupling باعث میشود restore etcd بدون revision bump برای controllers خطرناک باشد (بخش Disaster Recovery).
راهاندازی cluster
Static bootstrapping (۳ member)
# member 1
etcd --name m1 \
--initial-advertise-peer-urls http://10.0.0.1:2380 \
--listen-peer-urls http://10.0.0.1:2380 \
--listen-client-urls http://10.0.0.1:2379,http://127.0.0.1:2379 \
--advertise-client-urls http://10.0.0.1:2379 \
--initial-cluster m1=http://10.0.0.1:2380,m2=http://10.0.0.2:2380,m3=http://10.0.0.3:2380 \
--initial-cluster-state new \
--initial-cluster-token etcd-cluster-prod
# member 2, 3 — same token, different name/URLsPorts
| Port | کار |
|---|---|
| 2379 | client requests (gRPC/HTTP) |
| 2380 | peer communication (Raft) |
Discovery (alternative)
- etcd discovery service — bootstrap بدون static list
- DNS discovery — SRV records
Production معمولاً static یا operator-managed (etcd operator).
Hardware و tuning
etcd به disk write latency حساس است — نه CPU.
توصیه production
| Resource | Small (≤100 node K8s) | Medium | Large |
|---|---|---|---|
| CPU | 2 core | 4 core | 8–16 core |
| RAM | 8 GB | 16 GB | 32–64 GB |
| Disk | SSD، 50+ sequential IOPS | NVMe/PD SSD | Dedicated NVMe |
| Network | 1 GbE | 1 GbE | 10 GbE |
Disk: SSD/NVMe اجباری. 7200 RPM HDD برای production مناسب نیست. WAL fsync p99 < 10ms هدف.
# benchmark disk
fio --name=etcd-test --ioengine=sync --rw=write --bs=2300 \
--direct=1 --size=1G --numjobs=1 --fsync=1Quota و compaction
# default quota ~ 2GB (قابل تغییر)
--quota-backend-bytes=8589934592 # 8GB
# auto-compaction (Kubernetes 1.28+ default hourly)
--auto-compaction-retention=1h
# manual defrag (بعد از compaction)
etcdctl defrag --endpoints=$ENDPOINTSNOSPACE alarm: etcd full → read-only → cluster freeze. Monitor etcd_server_quota_backend_bytes.
Kubernetes stacked etcd tuning
# etcd Pod resources — control plane node
resources:
requests:
cpu: 100m
memory: 512Mi
limits:
memory: 2Gi # adjust by cluster sizeامنیت
TLS
# generate certs (cfssl یا kubeadm)
etcd --cert-file=server.crt \
--key-file=server.key \
--client-cert-auth \
--trusted-ca-file=ca.crt \
--peer-cert-file=peer.crt \
--peer-key-file=peer.key \
--peer-client-cert-auth \
--peer-trusted-ca-file=ca.crt- Client TLS — API server و etcdctl
- Peer TLS — Raft communication بین members
RBAC authentication
etcdctl user add root
etcdctl role add k8s-admin
etcdctl role grant-permission k8s-admin readwrite /registry
etcdctl user grant-role root k8s-admin
etcdctl auth enableKubernetes API server با client certificate اختصاصی authenticate میشود.
Monitoring
Metrics (Prometheus)
etcd_server_has_leader
etcd_server_leader_changes_seen_total
etcd_disk_wal_fsync_duration_seconds
etcd_disk_backend_commit_duration_seconds
etcd_mvcc_db_total_size_in_bytes
etcd_server_quota_backend_bytes
etcd_network_peer_round_trip_time_secondsAlert rules:
etcd_server_has_leader == 0— no leaderrate(etcd_server_leader_changes_seen_total[15m]) > 3— unstableetcd_disk_wal_fsync_duration_seconds p99 > 0.01— slow disketcd_mvcc_db_total_size_in_bytes / etcd_server_quota_backend_bytes > 0.8— quota warning
Health endpoints
etcdctl endpoint health
# 127.0.0.1:2379 is healthy: successfully committed proposal: took = 2.3ms
etcdctl alarm list
# NOSPACE, CORRUPTBackup و Disaster Recovery
Periodic snapshot اجباری — بدون backup، از دست دادن همه control plane = از دست دادن cluster state.
Snapshot
ETCDCTL_API=3 etcdctl \
--endpoints=https://127.0.0.1:2379 \
--cacert=/etc/kubernetes/pki/etcd/ca.crt \
--cert=/etc/kubernetes/pki/etcd/server.crt \
--key=/etc/kubernetes/pki/etcd/server.key \
snapshot save /backup/etcd-$(date +%Y%m%d-%H%M).db
# verify
etcdutl snapshot status /backup/etcd-20260902.db -w tableRestore (Kubernetes context)
# restore each member — same snapshot
etcdutl snapshot restore snapshot.db \
--name m1 \
--initial-cluster m1=https://10.0.0.1:2380,m2=https://10.0.0.2:2380,m3=https://10.0.0.3:2380 \
--initial-cluster-token etcd-restore-1 \
--initial-advertise-peer-urls https://10.0.0.1:2380 \
--data-dir /var/lib/etcd-restore \
--bump-revision 1000000000 \
--mark-compacted--bump-revision: revision به عقب برنگردد — informers/controllers cache invalidate شوند.
--mark-compacted: watchهای قدیمی terminate — controller resync کامل.
بعد از restore: API server --etcd-servers را update + restart control plane.
Quorum loss
N=5 → quorum=3
اگر ۳+ member permanently lost → cluster irrevocably failed
→ restore from snapshot روی cluster جدیدFailure modes
| Failure | تحمل |
|---|---|
| 1 minority member down | cluster continues |
| Network partition (minority isolated) | majority side continues |
| Leader crash | election → new leader (~seconds) |
| Slow disk | heartbeat timeout → election storm |
| Quota full (NOSPACE) | writes rejected — cluster read-only |
| Data corruption | CORRUPT alarm — restore from snapshot |
| Majority lost | disastrous — restore only option |
Maintenance
# member remove (online)
etcdctl member remove <member-id>
# member add
etcdctl member add m4 --peer-urls=http://10.0.0.4:2380
# leader transfer (graceful)
etcdctl move-leader <new-leader-id>Defrag: بعد از compaction — فضای disk آزاد. Rolling روی members — یکی یکی.
etcd در ecosystem
| پروژه | نقش etcd |
|---|---|
| Kubernetes | primary datastore — all cluster state |
| CoreDNS | etcd plugin — Skydns-compatible service discovery |
| Rook/Ceph | cluster config و coordination |
| M3 | metadata coordination |
| OpenShift | embedded + external patterns |
CoreDNS + etcd
skydns.local {
etcd {
path /skydns
endpoint http://etcd:2379
}
}برای service discovery خارج Kubernetes API — pattern قدیمی Skydns.
etcd vs Consul vs ZooKeeper
| etcd | Consul | ZooKeeper | |
|---|---|---|---|
| Primary use | K8s state | service mesh + KV | coordination (legacy) |
| Consistency | linearizable | strong | sequential |
| Protocol | Raft | Raft | ZAB |
| Watch | ✅ efficient | ✅ | ✅ |
| Multi-datacenter | limited | ✅ native | limited |
| Ops complexity | medium | medium | high |
برای Kubernetes control plane — etcd تنها انتخاب رسمی.
Best practices
- ۳ یا ۵ member — never 2، rarely 7
- Dedicated SSD/NVMe — etcd-only disk when possible
- Snapshot هر ۶–۲۴ ساعت — automate + encrypt + offsite
- Monitor WAL fsync latency — early warning
- Auto-compaction — prevent unbounded growth
- Separate external etcd — large clusters (>500 nodes)
- TLS everywhere — client + peer
- Revision bump on restore — Kubernetes controllers
- Don’t run heavy workloads on control plane nodes with stacked etcd
- Test restore — backup بدون tested restore بیفایده است
Troubleshooting
API server timeout
# etcd healthy?
etcdctl endpoint health -w table
# slow disk?
etcdctl check perf
# leader?
etcdctl endpoint status -w tableetcdserver: mvcc: database space exceeded
etcdctl alarm list
etcdctl alarm disarm # after compaction + defrag
etcdctl defrag --endpoints=...
# increase --quota-backend-bytesFrequent leader changes
- disk latency — check
etcd_disk_wal_fsync_duration_seconds - network RTT بین peers
- CPU starvation — increase limits
- misconfigured
--heartbeat-interval/--election-timeout
Member not joining
--initial-cluster-tokenmismatch- peer URL unreachable (2380)
- TLS cert SAN wrong
- data dir from old cluster identity
ارتباط با stack شما
Control plane
├── etcd ← all state (Pods, Services, Secrets, CRDs)
├── API server ← only etcd client
├── Scheduler / Controllers ← watch via API server
└── kubeadm static Pods
Data plane
├── kubelet → CRI ([containerd](/blog/containerd-container-runtime-guide/) / [CRI-O](/blog/cri-o-kubernetes-container-runtime-guide/))
├── CNI ([Cilium](/blog/cilium-ebpf-kubernetes-networking/))
└── DNS ([CoreDNS](/blog/coredns-kubernetes-dns-guide/))GitOps با Argo CD desired state را در Git نگه میدارد — اما observed state و live objects هنوز در etcd هستند.
cert-manager Certificates را در etcd persist میکند — backup etcd = backup TLS state cluster.
چه زمانی etcd مستقیم؟
✅ Kubernetes control plane
Built-in — راهی برای K8s بدون etcd نیست.
✅ Custom distributed coordination
- leader election
- distributed locks (lease)
- config propagation با watch
✅ Service discovery (non-K8s)
با CoreDNS etcd plugin یا client library.
⚠️ شاید جای دیگر بهتر باشد
- General-purpose cache → Redis
- Full service mesh + multi-DC → Consul
- Message queue → Kafka/NATS
- Relational queries → PostgreSQL
جمعبندی
| مفهوم | توضیح |
|---|---|
| etcd | strongly consistent distributed KV — Raft |
| Raft | leader + quorum — ۳/۵ member production |
| WAL + BoltDB + MVCC | durability + versioning |
| Kubernetes | API server exclusive client — all cluster state |
| Watch | informers و controllers |
| Snapshot | disaster recovery — encrypt + test restore |
| Disk | critical — SSD، fsync < 10ms p99 |
| CNCF | Graduated — CoreOS heritage |
etcd قلب تپنده Kubernetes است — kubectl get pods در نهایت یک read از etcd (via API server) است. درک Raft، backup، و disk performance تفاوت بین cluster پایدار و شبانهبیدار شدن روی leader election است.
منابع
- etcd — etcd.io
- etcd v3.6 Documentation
- Quickstart
- Operations Guide
- Hardware Recommendations
- Disaster Recovery
- Operating etcd clusters for Kubernetes
- GitHub — etcd-io/etcd
P30Light — زیرساخت، Kubernetes و etcd.