Fencing Tokens
1. Executive Summary
Fencing tokens are monotonically increasing numbers (or comparable epoch identifiers) issued by a lock service or consensus-backed coordinator when a client acquires exclusive authority—typically a distributed lease or leadership lock. Every subsequent write to a protected resource must carry the current token; the resource (database, block device, object store gateway) rejects operations whose token is less than the highest token it has already accepted.
Fencing closes a critical safety gap: a stale leader or expired lease holder can remain alive after failover and issue destructive writes unless the storage layer can distinguish fresh authority from stale authority. Leases alone provide liveness-oriented time bounds; fencing tokens provide safety-oriented rejection of stale actors at the resource boundary.
This chapter explains the split-brain problem that motivates fencing, formal safety properties, integration patterns with etcd, ZooKeeper, and Consul, failure scenarios including GC pauses and clock skew, and principal-level interview framing. Fencing is not a consensus algorithm—it is a defense-in-depth mechanism that makes lease-based leadership safe when paired with cooperative storage.
2. Why This Topic Matters
Distributed leases appear everywhere: Kubernetes leader election sidecars, database HA orchestration, job schedulers, and storage primaries. Interviewers and architecture reviewers probe whether candidates understand that "I hold the lock" is insufficient when the lock service and the data plane are separate systems.
Principal architects must articulate:
- Why lease expiry does not stop a paused process from writing.
- How fencing tokens differ from generation numbers, terms, and MVCC versions.
- Where fencing must be enforced (storage layer) versus where it is useless (application-only checks).
- Tradeoffs when the resource cannot enforce tokens (legacy databases, NFS, some object stores).
Production incidents from missing fencing include dual-primary databases, duplicate payment processing, and corrupted shared filesystems after failover. Kleppmann (Designing Data-Intensive Applications, Chapter 9) and operational postmortems from split-brain HA clusters are essential background.
3. Problems Being Solved
| Problem | Fencing mechanism |
|---|---|
| Stale leader writes after failover | Resource rejects writes with token < max seen |
| GC pause longer than lease TTL | Expired holder's writes fail at storage |
| Network partition with lease holder isolated | New leader gets higher token; old writes fenced |
| Delayed messages from prior epoch | Monotonic token invalidates stale operations |
| Application believes it is still primary | Storage is source of truth for accepted token |
Fencing does not solve Byzantine faults, application-level idempotency without tokens, or resources that ignore fencing entirely.
4. Assumptions and System Model
| Assumption | Fencing treatment |
|---|---|
| Crash-stop or fail-stop processes | Stale process may resume; fencing handles delayed writes |
| Lock service provides monotonic tokens | Typically via consensus (Raft term, ZK sequential znode) |
| Resource enforces token check atomically with write | Required for safety; check-then-act at app layer is insufficient |
| Single-writer resource semantics | Fencing targets exclusive writers (block device, primary DB) |
| Not Byzantine | Malicious clients forging tokens breaks model |
Client model: Lock holder obtains token T from coordinator; each write includes T; resource updates max_token on accept and rejects T' < max_token.
Not assumed: Universal support in all storage systems; automatic fencing without application integration; fencing across multi-leader databases without additional coordination.
5. Essential Terminology
| Term | Definition |
|---|---|
| Fencing token | Monotonic identifier proving freshness of write authority |
| Lock service | Coordinator issuing tokens (etcd, ZooKeeper, Consul) |
| Resource / storage layer | System that must reject stale tokens |
| Stale leader | Node that lost authority but has not yet stopped writing |
| Split brain | Two nodes both believing they have write authority |
| Lease | Time-bounded lock; often paired with fencing |
| Generation number | Similar concept in GFS, HDFS block generations |
| Epoch / term | Consensus logical clock; can serve as fencing epoch |
| Check-and-set | Compare token before write; must be atomic with write |
| Fail-closed | Reject ambiguous writes rather than accept |
| Lock delay | Intentional wait before new primary writes (weak substitute) |
| STONITH | Shoot The Other Node In The Head—hardware fencing alternative |
Distinction: A lease tells the holder when to stop; a fencing token tells the resource which holder to accept.
6. Core Mechanism
6.1 The stale lease holder problem
A process holds a lease on a coordination service. Before the lease expires, it experiences a long stop-the-world GC pause or VM freeze. The lease expires; a new primary acquires a higher token and begins writing. The old process resumes, still believing it holds the lease, and writes to the database—without checking the coordinator on every write path.
Figure 1: Without fencing, a stale primary can corrupt state after lease transfer.
6.2 Fencing token flow
- Client requests lock; coordinator returns token T (monotonic).
- Client includes T on every write to the resource.
- Resource maintains
max_accepted_token. - If
T < max_accepted_token, reject write (fail closed). - If
T >= max_accepted_token, apply write and setmax_accepted_token = T.
Figure 2: Storage rejects stale token—fencing contains the failure.
6.3 Where tokens come from
| Source | Token shape | Notes |
|---|---|---|
| etcd lease + revision | MVCC revision or custom counter | Linearizable grant path |
| ZooKeeper sequential node | Sequence number in znode name | lock-0000000042 |
| Raft term + index | Composite epoch | Used in consensus-native systems |
| Consul session + KV | Session lock with monotonic session ID | Pair with app-side enforcement |
| Dedicated token service | Central counter | Must itself be highly available |
The token must increase every time exclusive authority transfers, including after crash recovery of the coordinator (consensus-backed counters survive restarts).
6.4 Enforcement location
Correct: Storage engine, SAN controller, distributed filesystem metadata server, or database extension that atomically compares token with write.
Insufficient: Application checks token in memory before calling an unfenced API; race between check and write.
Figure 3: Fencing must be enforced at the resource boundary, not only in application logic.
7. Step-by-Step Walkthrough
Walkthrough A: Normal failover with fencing
- Primary P1 holds lock, token 100. Storage
max_token=100. - P1 writes
{data: v1, token: 100}→ accepted. - P1 fails health checks; lease expires.
- P2 acquires lock, token 101.
- P2 writes
{data: v2, token: 101}→ accepted;max_token=101. - P1 recovers (was partitioned), attempts
{data: v3, token: 100}→ rejected.
Walkthrough B: GC pause without fencing (failure)
- P1 holds lease, writes successfully.
- 90-second GC pause; lease TTL 30 seconds.
- P2 becomes primary, writes new state.
- P1 resumes, writes without re-validating lock → split brain if storage unfenced.
Walkthrough C: etcd lease + custom token column
- Application uses etcd concurrency API or lease on a key.
- On leadership grant, read revision or maintain counter in etcd via atomic transaction.
- PostgreSQL table includes
fencing_token BIGINT; trigger rejectsNEW.token < current_max.
Walkthrough D: Block storage (iSCSI / SAN)
- Cluster manager issues reservation key or persistent reservation generation.
- Only holder with current key may issue SCSI writes.
- Failover increments reservation generation; old host I/O fails at array.
Walkthrough E: When fencing is impossible
Legacy MySQL async replication without shared-storage fencing: operators use VIP drain, iptables, STONITH, or manual promotion with lock delay—weaker than token enforcement. Document residual risk.
Walkthrough F: Token scope across microservices
In a sharded system, each shard primary may hold a separate lock path (/locks/shard/7). The coordinator issues independent token sequences per shard or a global counter depending on design:
- Per-shard tokens: Shard 7's storage tracks
max_tokenonly for shard 7; failover on shard 7 does not affect shard 12. - Global tokens: Simpler reasoning for shared storage arrays; higher coordination contention on lock acquisition.
Architects document token scope in ADRs so on-call engineers know which resource rejects which token stream during incident response.
Walkthrough G: Read-only stale primary
Fencing primarily protects writes. A stale primary may still serve reads from local cache after losing the lease—dangerous if reads drive billing or inventory decisions. Mitigations: read from leader only, version checks, or terminate stale instance via orchestrator health checks tied to lease validity.