Markdown Editor

Distributed Lock and Coordination System Design Template

Lock and coordination service: Raft consensus, read index, sessions and keep-alives, leader election, fencing tokens, watches, read scaling, misuse policy

Cara menggunakan: Use it when building or adopting a coordination service for leader election, locks, configuration and discovery. Fill the session, keep-alive and watch counts first, because keep-alives and notification fan-out overload these services before bytes do. The main pitfall is trusting a lock without a fencing token checked by the protected resource.

Pratinjau

System Design: [Coordination service name]

Reference design for a distributed lock and coordination service: a small, strongly consistent, replicated store that other systems use for leader election, locks with leases, fencing tokens, configuration, membership and change notification. It covers consensus with Raft (or Multi-Paxos), sessions and keep-alives, failover grace periods, watches, read scalability and the ways teams misuse such a service. Concepts draw on the Chubby lock service (Burrows, OSDI 2006), the Raft paper (Ongaro and Ousterhout, USENIX ATC 2014), ZooKeeper (Hunt et al., USENIX ATC 2010) and the etcd v3.6 API documentation; the text and the worked design are original. It follows the structure of the System Design Document template. Replace every [bracketed] value and every row marked Example.

Document control

FieldValue
Document ID[SDD-COORD-001]
System / feature[Coordination service for leader election, locks and configuration]
Version[0.1]
Status[Draft / In review / Approved / Implemented / Superseded]
Owner[@owner]
Author(s)[@author]
Reviewers[@reviewer-1], [@reviewer-2]
Last updatedYYYY-MM-DD
Classification[Internal; tier-0 dependency]
Consistency model[Example: Linearizable writes and reads by default; serializable reads opt-in]
RelatedDistributed Key-Value Store System Design (system-design/design-distributed-kv-store), Job Scheduler System Design (system-design/design-job-scheduler), Message Queue System Design (system-design/design-message-queue)

Approvals

RoleNameDecisionDate
Tech lead[@name][Approved / Changes requested]YYYY-MM-DD
Staff / principal engineer[@name][Decision]YYYY-MM-DD
SRE / operations[@name][Decision]YYYY-MM-DD
Security[@name][Decision]YYYY-MM-DD
Platform consumers' representative[@name][Decision]YYYY-MM-DD

Revision history

VersionDateAuthorChange summary
0.1YYYY-MM-DD[@name]First draft for design review
0.2YYYY-MM-DD[@name]Example: Added fencing tokens after a split-brain write in the scheduler
0.3YYYY-MM-DD[@name]Example: Added proxy tier to absorb keep-alives and watch fan-out
1.0YYYY-MM-DD[@name]Example: Approved

Contents

1. Overview

1.1 Problem statement

[Example: Teams implement leader election with database row locks, cache-based locks with TTLs, and hand-written heartbeats. Last quarter two scheduler instances both believed they were leader after a long garbage collection pause and ran the same billing job twice. Configuration is pushed by redeploying, and service discovery lags by minutes.]

1.2 Proposed solution

[Example: A coordination service runs as cells of five replicas across three zones, replicated with Raft. It exposes a small hierarchical key-value store with revisions, sessions held alive by keep-alives, locks and elections built on sessions, and watches that stream changes from a given revision. Every lock acquisition returns a fencing token (the lock key's revision) that protected resources must check. A stateless proxy tier absorbs keep-alives and fans out watch notifications. Values are capped at Example 64 KB and the service is explicitly not a general data store.]

1.3 Decisions requested from reviewers

IDQuestionRecommended optionSection
Q-01Example: Which consensus protocol?Raft, using a mature open-source implementation7.1
Q-02Example: How are reads made linearizable without a log write?Leader confirms leadership with a quorum before serving (read index)7.1
Q-03Example: What protects resources from a stale lock holder?Fencing tokens checked by the resource7.3
Q-04Example: Session TTL and keep-alive interval?30 s TTL, keep-alive every 10 s, grace period across leader failover7.2
Q-05Example: Cell size?5 voting replicas in 3 zones3.6, 9.1
[Q-nn][Question][Option][Section]

1.4 45-minute interview path

MinutesCoverOutput on the whiteboard
0 to 5What clients need: leader election, locks, config, discovery; consistency expectationCore requirements FR-01 to FR-06
5 to 10Sessions, keep-alives, writes, reads, watchesKeep-alives dominate; one leader takes all writes
10 to 18Cell, proxies, clients diagramSection 6 diagram
18 to 33Deep dive: consensus and linearizable reads (7.1) and locks with fencing tokens (7.3); if the interviewer asks about scale, use watches and read scaling (7.4)Raft roles, fencing sequence
33 to 40Session failover and misuse pitfallsGrace period, usage policy
40 to 45Trade-offs and 10xTable in section 10

2. Requirements

2.1 Core functional requirements

IDRequirementPriority
FR-01Example: Store small keys and values with a global revision on every changeMust
FR-02Example: Atomic compare-and-set transactions on one or more keysMust
FR-03Example: Sessions with TTL kept alive by clients; ephemeral keys deleted when the session endsMust
FR-04Example: Exclusive locks and leader election returning a fencing tokenMust
FR-05Example: Watches on a key or prefix from a given revision, with no missed eventsMust
FR-06Example: Linearizable reads by defaultMust
FR-07Example: Shared (reader) locksShould
FR-08Example: Serializable (possibly stale) reads for discovery and configShould
[FR-nn][Requirement][Must / Should / Could]

2.2 Non-functional requirements

IDQualityTargetMeasured as
NFR-01AvailabilityExample: 99.99% per cell; tolerate loss of one zoneSynthetic lock acquire every 10 s
NFR-02Write latencyExample: p99 below 25 ms within a regionServer and client histograms
NFR-03FailoverExample: New leader within 5 s; no healthy client session expires during failoverFailover drill
NFR-04SafetyExample: Never two holders of an exclusive lock whose fencing tokens are both accepted by the resourceFault-injection tests with partitions and process pauses
NFR-05Watch deliveryExample: p99 below 1 s from commit to notification for 100 000 watchersProbe keys
[NFR-nn][Quality][Target][Measurement]

2.3 Below the line (out of scope)

  • [Example: Storing application data, queues or large blobs (see system-design/design-distributed-kv-store and system-design/design-message-queue)]
  • [Example: Fine-grained locks held for milliseconds per request]
  • [Example: Cross-region linearizability within one cell; each region runs its own cell, with one global cell for rare global decisions]
  • [Example: Rate limiting and counters at request rates]
  • [Item deferred, with the release that will take it]

3. Capacity estimation

3.1 Assumptions

InputSymbolValueSource
Client sessions per cellSSExample: 100 000Service instances x processes
Keep-alive intervaltkt_kExample: 10 s (TTL 30 s)7.2
Writes per second (locks, elections, config, registrations)WWExample: 2 000Onboarding survey
Reads per secondQQExample: 50 000Onboarding survey
Watches per sessionwwExample: 5Client library defaults
Keys and average value sizeKK, vvExample: 1 million, 1 KBOnboarding survey
Log fsync latency on target disksffExample: 2 msBenchmark
Notifications sent per second per servernnExample: 20 000Benchmark

3.2 Keep-alives

KA=Stk=100 00010 s=10 000 keep-alives/sKA = \frac{S}{t_k} = \frac{100\,000}{10\ \text{s}} = 10\,000\ \text{keep-alives/s}

Keep-alives refresh leases, and lease refreshes are handled by the leader. Consequence: keep-alives alone are five times the write rate, so a proxy tier terminates client sessions and refreshes them upstream in batches; the cell sees one stream per proxy instead of one per client.

3.3 Writes

Every write is appended to the replicated log and fsynced by a quorum. One fsync per write would cap throughput near 1/f=5001 / f = 500 writes/s per replica; group commit batches entries:

entries per batch=W×f1=2 000×0.002=4\text{entries per batch} = \frac{W \times f}{1} = 2\,000 \times 0.002 = 4

Consequence: batching makes 2 000 writes/s easy, but all writes go through one leader, so adding replicas does not add write capacity (it adds latency). Write growth is handled by more cells partitioned by tenant, not bigger cells.

3.4 Reads and watches

Reads at 50 000/s are 25 times the write rate. Consequence: reads must be served by followers and proxies, using read-index confirmation for linearizable reads and local state for serializable ones (7.1, 7.4).

Watches: S×w=500 000S \times w = 500\,000 watches; at about 200 B each that is about 100 MB of memory, which is small. Fan-out is the risk: a change to a key watched by all 100 000 sessions creates 100 000 notifications, which take one server 100 000/20 000=5100\,000 / 20\,000 = 5 s to send. Consequence: watches register at proxies, so the cell sends one notification per proxy and proxies fan out in parallel; clients add jitter before re-reading so the change does not create a read herd.

3.5 Data size and snapshots

K×v=106×1K \times v = 10^{6} \times 1 KB =1= 1 GB, kept in memory with the log on SSD. Consequence: cap the keyspace at Example 2 GB; a new or lagging replica installs a snapshot of that size in about 20 s at 100 MB/s, which keeps replacement of a failed replica quick. Enforce value size limits and per-tenant quotas to hold the cap.

3.6 Cell size

A cell of 2F+12F + 1 voting replicas tolerates FF failures. Five replicas across three zones (2 + 2 + 1) survive the loss of any one zone or of any two replicas. Three voters in three zones also survive a zone loss, but only one replica failure. Consequence: five voters, not three, so that one replica can be down for a planned upgrade while another fails unexpectedly.

3.7 Summary

QuantityEstimateDesign consequence
Keep-alives10 000/sProxy tier aggregates sessions
Writes2 000/sGroup commit; scale by more cells, not bigger cells
Reads50 000/sFollower reads with read index; proxy caches
Watch fan-out100 000 per hot key change, 5 s from one serverProxies fan out; client jitter
Data~1 GB in memoryKeyspace cap 2 GB; value size limit
Cell5 voters in 3 zonesSurvives a zone loss

4. API design

4.1 Operations

OperationConsistencyNotes
Session.Create(ttl)LinearizableReturns session ID; server may adjust TTL
Session.KeepAlive(id) (stream)LeaderReturns remaining TTL
KV.Get(key, serializable = false)Linearizable by defaultReturns value, create_revision, mod_revision
KV.Range(prefix, at_revision?)Linearizable or at a past revisionBounded page size
KV.Txn(compares, then, else)LinearizableCompares on value, version or revisions
Lock.Acquire(name, session, timeout)LinearizableReturns fencing token
Lock.Release(name, token)LinearizableIdempotent
Election.Campaign(name, session, value)LinearizableBlocks until leader; returns token
Election.Observe(name) (stream)Watch semanticsCurrent leader and changes
Watch(key or prefix, from_revision) (stream)Ordered, resumableFails with compacted if the revision is too old

4.2 Lock acquisition as a transaction

A lock is a key created only if it does not exist, attached to the caller's session so it disappears if the session ends:

Txn(
  compare: create_revision("locks/billing-run") == 0
  then:    put("locks/billing-run", owner="sched-7", session=S123)
  else:    get("locks/billing-run")
)
-> succeeded: token = header.revision (for example 482113)
-> failed:    watch "locks/billing-run" for delete, then retry

For fair queuing, each waiter instead creates locks/billing-run/{session} and the holder is the key with the lowest create_revision; each waiter watches only the key just before it, so a release wakes one waiter, not all.

4.3 Protected resource check

The resource, not the lock service, enforces exclusion. It stores the highest token it has accepted per protected object and rejects anything lower:

WriteJobResult(job_id, result, fencing_token = 482113)
  if fencing_token < last_seen_token[job_id]: reject (stale holder)
  else: last_seen_token[job_id] = fencing_token; apply

4.4 Errors

ErrorMeaningClient action
session_expiredSession TTL passed without keep-aliveStop work guarded by its locks; create a new session
not_leaderRequest reached a follower that cannot serve itRetry via proxy
compactedWatch revision older than retained historyRe-read current state, then watch from its revision
quota_exceededTenant key count or size limitReduce usage; request quota
value_too_largeAbove size limitStore data elsewhere, keep a pointer

5. Data model

5.1 Replicated state

All state is one replicated state machine per cell, built from the Raft log:

The cell keeps a single 64-bit revision counter that increases with every committed change; it orders all changes and serves as the fencing token source. Watches live in proxy and server memory, not in the replicated state.

5.2 Storage choices

DataStoreWhy
Raft logAppend-only files on local SSD, fsyncedDurability of every committed entry
State machineIn-memory index plus an embedded B-tree or LSM file with multi-version keysFast reads; reads at past revisions until compaction
SnapshotsLocal files, copied to object storage for disaster recoveryReplica catch-up and restore
Session and lease expiryLeader memory, rebuilt from state on electionLeader alone expires sessions; followers do not

5.3 Access patterns

Access patternServed byKey layout and rationale
Who is leader of scheduler?Lowest create_revision under elections/scheduler/Per-candidate keys avoid herds; order by revision is total
Acquire lock billing-runTxn on locks/billing-runOne key per lock; attached to session
Read all config for a serviceRange config/{service}/Prefix per service keeps reads to one range
List live instancesRange members/{service}/ of ephemeral keysSession expiry removes dead instances
Follow config changesWatch prefix config/{service}/ from the read revisionRead then watch from that revision: nothing missed
Tenant usageCounters per top-level prefix {tenant}/Quotas enforced at write time

6. High-level design

ComponentResponsibilityScales by
Client librarySessions, keep-alive, lock and election recipes, fencing tokens, watch resumeWith clients
Proxy tierTerminate sessions, batch keep-alives, cache reads, share watchesProxy instances
LeaderOrder all writes, expire sessions, confirm leadership for readsOne per cell
FollowersReplicate log, serve reads with read index, serve watchesUp to 5 voters; non-voting replicas for reads
Snapshot backupDisaster recoveryObject storage

7. Detailed design

7.1 Deep dive: consensus and linearizable reads

OptionHow it worksStrengthWeakness
A. Primary-backup with external failure detectorOne primary, backups copy; an external system picks a new primarySimple data pathNeeds another consensus system to decide failover; split-brain risk
B. Multi-PaxosReplicas agree on each log slot; a stable leader optimises the common caseProven; flexibleMany variants; hard to implement and reason about
C. RaftStrong leader, randomized election timeouts, log matching, joint consensus for membershipDesigned for understandability; many mature implementationsLeader is a throughput bottleneck
D. Atomic broadcast as in ZooKeeper (ZAB)Leader broadcasts ordered updates; recovery protocol on leader changeProven at scaleTied to one implementation family

Choice: C, using a mature implementation rather than writing one. Reason: the team must operate and debug the protocol during incidents; Raft's structure (leader election, log replication, safety) is easier to reason about, and its membership-change procedure supports replacing replicas without downtime.

Linearizable reads have three options:

Read optionHowCostRisk
Through the logAppend a read entry and wait for commitOne quorum write per readSlow, expensive
Read indexLeader records commit index, confirms it is still leader with a quorum heartbeat, then the replica serves once it has applied up to that indexOne round of heartbeats, batched across readsNone beyond normal Raft assumptions
Leader leaseLeader serves reads alone while its lease (based on election timeout) has not expiredNo network roundDepends on bounded clock drift; unsafe if clocks jump

Choice: read index by default, leader lease off. Reason: the extended Raft paper describes confirming leadership with a majority before answering a read and notes that relying on a lease makes safety depend on timing; for a lock service, safety wins over a fraction of a millisecond. A new leader commits a no-op entry at the start of its term before serving reads, so it knows which entries are committed.

7.2 Deep dive: sessions, keep-alives and failover

Sessions tie ephemeral keys and locks to a live client. A session ends when no keep-alive arrives before its TTL; then its ephemeral keys and locks are deleted in one committed transaction, so watchers see a consistent change.

ParameterExample valueReasoning
Session TTL30 sLonger than leader failover plus network blips
Keep-alive interval10 sThree chances before expiry
Election timeout1 to 2 s randomizedCross-zone round trips; Raft paper suggests 150 to 300 ms for LAN-scale clusters
Client grace period45 s of retrying after losing contactSurvive failover; resume only if the cell confirms the session still exists

During leader failover no keep-alive is acknowledged. Two measures keep healthy sessions alive:

  1. A new leader does not expire any session until it has given every session at least one full TTL from its election (session expiry is extended on leadership change).
  2. The client library, on losing contact, enters a "jeopardy" state: it tells the application that its locks may be at risk, pauses work that needs them, and keeps trying other replicas for the grace period. If contact returns and the cell confirms the session is still alive, work resumes; if the session expired or the grace period ends, the application treats its locks as lost.

The application must also stop acting on a lock when its own process paused (garbage collection, VM migration). Timeouts on the client cannot detect that reliably, which is why fencing tokens (7.3) exist.

7.3 Deep dive: locks, leader election and fencing tokens

A lock gives mutual exclusion in the coordination service, not at the resource. A holder can be paused after it last checked its session, wake up after the session expired and another client took the lock, and still send a write.

OptionHow it worksProtects against paused holder?
A. TTL lock in a cacheSet-if-absent with expiryNo; also unsafe on cache failover
B. Coordination-service lock onlySession-bound keyNo; only the service knows who holds it
C. Lock-delayAfter a holder's session expires, the lock cannot be taken for a short periodReduces risk; does not remove it
D. Fencing token checked by the resourceToken = lock key's revision; resource rejects lower tokensYes, if every write path checks it

Choice: D for every lock that guards a side effect, with C as an extra margin for resources that cannot check tokens yet. Reason: only the resource can reject a stale write after the fact. Teams that cannot add a token check must design the work to be idempotent instead.

Leader election uses the same recipe: each candidate creates an ephemeral key under elections/{name}/; the lowest create_revision leads and its revision is the leader epoch, used as the fencing token for everything the leader writes. Followers watch only their predecessor.

7.4 Deep dive: watches, caching and read scalability

OptionHow it worksStrengthWeakness
A. PollingClients re-read every few secondsSimpleLoad grows with clients; staleness equals interval
B. One-shot watchesNotification once; client re-reads and re-registersSimple serverChanges between notification and re-register must be detected by version check
C. Revision-based streaming watchesStream every change after a given revision; resumable after disconnectNothing missed; orderedHistory must be retained until compaction
D. Client cache with server invalidationServer invalidates cached entries before a write completesVery low read loadWrite waits for invalidations; complex

Choice: C, served by followers and proxies, plus small proxy caches for serializable reads. Reason: read-then-watch-from-revision gives clients a gap-free view; proxies merge identical watches so the cell sees one per proxy. Keep history for Example 1 hour; a watcher that falls further behind gets compacted and must re-read.

Read scaling ladder, in order:

  1. Serializable reads from any follower for discovery and config that tolerate staleness.
  2. Read-index linearizable reads on followers.
  3. Proxy caches kept current by watches.
  4. Non-voting replicas (learners) that replicate the log and serve reads without slowing commits.
  5. More cells, partitioned by tenant.

7.5 Misuse pitfalls and usage policy

PitfallWhy it hurtsPolicy
Using the service as a databaseLarge values and high write rates slow every tenant's electionsValue cap 64 KB; per-tenant quotas; reviews for any write rate above 50/s
Fine-grained locks per requestWrite rate explodes; latency on every requestCoarse locks held for minutes or hours; per-request coordination elsewhere
Lock without fencingPaused holder corrupts the resourceFencing token or idempotent work required
Everyone watches one key and re-reads at onceNotification and read herdProxies; jitter; watch predecessor only in queues
Short session TTLs "for faster failover"Sessions expire during routine leader changesTTL at least 3x keep-alive and above failover time
Treating a cell as globalCross-region latency on every writeOne cell per region; a global cell only for rare decisions
Assuming the service is always upHard dependency in every request pathCache last known config; leaders keep working through short outages only when fenced

7.6 How real systems do it

How real systems do it (paraphrased, not copied). Burrows describes Google's Chubby in "The Chubby Lock Service for Loosely-Coupled Distributed Systems" (OSDI 2006). Chubby is aimed at coarse-grained locking and small files, with cells of typically five replicas that use Paxos to elect a master holding a master lease. Clients keep sessions alive with keep-alives; when a client loses contact, its library signals jeopardy and waits through a grace period (45 s by default in the paper) so sessions survive master failover. Lock holders can obtain a sequencer that servers check before acting, with a lock-delay as a weaker fallback for servers that do not check. Clients cache data and the master invalidates caches before changes complete; proxies can absorb keep-alives and reads. Separately, Ongaro and Ousterhout's "In Search of an Understandable Consensus Algorithm" (USENIX ATC 2014) defines Raft, decomposing consensus into leader election, log replication and safety; its extended version covers linearizable read handling. This template reuses the ideas, not the text or figures.

8. Scalability and performance

ConcernApproachLimit before redesign
WritesGroup commit; small valuesLeader disk and CPU; Example: about 10 000 small writes/s per cell
Keep-alivesProxy aggregationProxy count and session churn on proxy restarts
ReadsRead index on followers, proxies, learnersHeartbeat batching on the leader
WatchesProxy sharing, jitterNotification fan-out per server
Data sizeQuotas, 2 GB capSnapshot install time for new replicas
TenantsSeparate cells per tenant groupOperational cost per cell

Write latency budget (NFR-02, Example): client to proxy 0.5 ms, proxy to leader 0.5 ms, leader append and parallel replication to the fastest two followers across zones 2 ms plus fsync 2 ms, apply 0.2 ms, response path 1 ms; about 6 ms typical, with headroom for cross-zone variance up to the 25 ms p99.

9. Reliability, security and operations

9.1 Failure-mode table

ComponentFailureDetectionBlast radiusMitigationRTO
LeaderCrashFollowers miss heartbeatsWrites and linearizable reads pauseRaft election; sessions extended on new leaderExample: under 5 s
One zoneOutageReplica healthUp to two of five votersRemaining three keep quorumNo interruption beyond election
Two zonesOutageQuorum lostWhole cell read-only or downClients run on cached config; documented manual recovery from snapshotExample: 1 h manual
DiskSlow fsyncCommit latencyAll writesDedicated SSD; alert; replace replicaExample: 30 min
ProxyCrashHealth checksIts sessions must reconnectClients reconnect to another proxy within the grace periodExample: 10 s
ClientLong pauseSession expiryIts locks move to another clientFencing tokens reject its late writesImmediate
TenantAbusive write ratePer-tenant metricsEvery tenant's latencyQuotas and rate limits per tenantExample: 1 min
[Component][Failure][Signal][Scope][Mitigation][Time]

9.2 Security

ThreatControl
Unauthorised lock or config changemTLS for clients and peers; role-based access per prefix
Peer impersonationPeer certificates pinned to cell membership
Secrets stored as config valuesProhibited by policy; secret manager instead; scanner on writes
Snapshot theftEncrypted backups with restricted access
Denial of service by one tenantQuotas, request limits, separate cells for critical tenants
[Threat][Control]

9.3 Observability

SignalMetricAlert threshold
LeadershipLeader changes per hourExample: more than 3
Commit latencyp99 proposal to commitAbove 25 ms for 5 min
Follower lagApplied index behind leaderAbove 1 000 entries
SessionsExpirations per minuteSpike above baseline x 5
WatchesNotification delayAbove 1 s at p99
SizeKeyspace bytes vs capAbove 70%

10. Trade-offs and alternatives

DecisionOptionsChosenWhyWhat we give up
ConsensusPrimary-backup; Multi-Paxos; Raft; ZAB-likeRaftUnderstandable, mature implementationsLeader-bound writes
Linearizable readsVia log; read index; leader leaseRead indexSafe without clock assumptionsOne heartbeat round per read batch
Lock safetyLock only; lock-delay; fencingFencing (+ lock-delay fallback)Only the resource can reject stale writesEvery resource must check tokens
NotificationsPolling; one-shot; streaming from revisionStreaming from revisionGap-free and resumableHistory retention
Build or adoptWrite own; adopt etcd, ZooKeeper or Consul; managed[Choice][Reason][Cost]
At 10x load1 million sessions, 20 000 writes/sPartition by tenant into several cells; more proxies; learners for readsOne leader cannot take 10x writesMore cells to run and to place tenants on
At 0.1x load10 000 sessions, 200 writes/sOne 3-voter cell may suffice if one zone loss is the only target; no proxy tierLower costCannot tolerate a second failure while one replica is down for maintenance

11. Delivery plan and risks

11.1 Milestones

MilestoneScopeExit criterionTarget date
M1Cell, client library with sessions, locks and fencing tokensSafety test suite passes with partitions and pausesYYYY-MM-DD
M2Scheduler and job runner migrate (system-design/design-job-scheduler)No duplicate runs in 30 daysYYYY-MM-DD
M3Proxy tier, watches, config and discovery100 000 sessions in load test; NFR-05 metYYYY-MM-DD
M4Second cell, tenant placement, quotasFailover drill per cell passesYYYY-MM-DD

11.2 Rollout and rollback

[Example: Each consumer migrates behind a flag that selects the old or new election mechanism; both run in observe-only mode for a week and must agree on the leader. Rollback flips the flag; the old mechanism stays deployed until the migration is complete for 30 days.]

11.3 Risks

IDRiskLikelihoodImpactMitigationOwner
R-01Example: Teams skip fencing token checksHighHighLibrary makes token mandatory; review checklist[@name]
R-02Example: Service becomes a dumping ground for dataMediumHighQuotas, value cap, usage policy (7.5)[@name]
R-03Example: Hot watch key overloads proxiesMediumMediumJitter, watch sharing, load test[@name]
R-04Example: Quorum loss in a regional disasterLowHighCached config in clients; restore runbook[@name]
[R-nn][Risk][L / M / H][L / M / H][Mitigation][@name]

12. Appendices

12.1 Open questions

IDQuestionOwnerDue
OQ-01Example: Which existing resources can check fencing tokens, and which need idempotency instead?[@name]YYYY-MM-DD
OQ-02Example: Do we need a global cell, or can all decisions be regional?[@name]YYYY-MM-DD
[OQ-nn][Question][@name]YYYY-MM-DD

12.2 Glossary

TermMeaning
CellOne replicated group of servers that forms a quorum
SessionClient's liveness lease, renewed by keep-alives
Ephemeral keyKey deleted automatically when its session ends
Fencing tokenMonotonic number from the lock grant that resources compare to reject stale holders
Read indexCommit index the leader confirms with a quorum before a linearizable read is served
JeopardyClient state after losing contact, before the session is declared lost
LearnerNon-voting replica that receives the log and serves reads
CompactionRemoval of old revisions from history
[Term][Meaning]

12.3 Related templates

  • Distributed Key-Value Store System Design (system-design/design-distributed-kv-store): for data that does not belong here.
  • Job Scheduler System Design (system-design/design-job-scheduler): main consumer of leader election and fencing.
  • Message Queue System Design (system-design/design-message-queue): controller election and partition metadata.
  • Stream Processing Engine System Design (system-design/design-stream-processing-engine): coordinator leader and checkpoint pointer.
  • Distributed Cache System Design (system-design/design-distributed-cache): slot map storage.

12.4 References

ReferenceUse
Burrows M., "The Chubby Lock Service for Loosely-Coupled Distributed Systems", OSDI '06, 2006Coarse locks, sessions, grace period, sequencers, lock-delay, proxies (7.2, 7.3, 7.6)
Ongaro D., Ousterhout J., "In Search of an Understandable Consensus Algorithm", USENIX ATC '14, 2014, and its extended versionRaft, election timeouts, read-only handling (7.1, 7.6)
Hunt P. et al., "ZooKeeper: Wait-free Coordination for Internet-scale Systems", USENIX ATC '10, 2010Watches and coordination recipes (7.4)
etcd v3.6 documentation, API guarantees and API referenceRevisions, leases, watches from a revision, transactions (4, 5, 7.4)
Kleppmann M., "How to do distributed locking", 8 February 2016Fencing token argument (7.3)

Standard and licence note

Based on the publicly described designs and documentation cited in 12.4 (Chubby, Raft, ZooKeeper, etcd v3.6); no standard governs coordination services. This is a reference design to adapt, with illustrative numbers marked Example. Original text written for this collection; sources were used as inspiration only and no text, figures or diagrams were copied. Check the current documentation of any implementation you adopt, because API details change between releases. Template licence: MIT.

Templat terkait