We are asked: "Design a distributed lock service: fencing tokens, TTLs, and failure modes." This is a classic distributed systems design question. We need to produce an answer. The user likely expects a description of a distributed lock service, explaining fencing tokens (used to prevent split-brain or stale clients from making changes), TTLs (time-to-live for locks to expire automatically), and failure modes (what can go wrong: network partitions, client failures, clock skew, etc., and how we handle them). Possibly also talk about implementation details: using consensus algorithm (Raft, Paxos) or using a quorum-based approach (like Redis Redlock). But the question says "Design a distributed lock service: fencing tokens, TTLs, and failure modes." So we need to cover these aspects.
We need to produce a structured answer. Could include:
- Introduction: purpose of distributed lock.
- System model: assume asynchronous network, possible failures.
- Design goals: correctness (mutual exclusion, progress), safety, liveness.
- High-level architecture: lock servers (maybe a cluster), clients, API (acquire, release).
- Fencing tokens: explained as monotonic increasing numbers or unique IDs to prevent old clients from interfering after they lose lock but still think they hold it. Use of token in operations on protected resource to ensure only latest lock holder can perform actions. Or using version numbers.
- TTL: locks have expiration time. Clients must periodically renew (lease) or the lock automatically releases after TTL. TTL prevents deadlocks due to client crash.
- Failure modes:
- Client failure after acquiring lock: TTL ensures eventual release.
- Network partition: split-brain scenario where two clients think they hold lock. Need to ensure at most one active. Using fencing tokens: if both have lock, token order determines which is legitimate. Also TTL helps: one side's lock expires.
- Clock skew: TTL depends on time. Could cause early expiration or extended hold. Use relative time (lease duration) from server's clock, not client's.
- Server failure: need replication. Use consensus (Raft) for lock state to survive failures. Split-brain among servers? Use quorum.
- Lost release messages: client releases but message lost, lock remains until TTL. Acceptable.
- Client clock vs server clock: TTL based on server time.
- Additional considerations: fairness, fairness maybe not needed. Use of unique client IDs. Fencing token generation: by lock service, monotonically increasing.
- Implementation: Could be based on a replicated state machine (R.SM). Acquire: client sends request with lease time; if granted, server returns fencing token. Release: client sends token; server checks token matches current. Renew: extend TTL.
- Handling concurrent acquire: use lease with expiration; if conflict, one gets lock with token. Use of compare-and-set for release.
We should also discuss the trade-offs: overhead of consensus for each lock operation. Possibly allow local cache of lock state? No, need consistency.
We need to produce a final answer: explanation of design with focus on fencing tokens, TTL, failure modes. Possibly include diagrams? Not needed. Text description.
Let's structure:
- Problem Statement: Need a service that provides mutual exclusion among distributed processes.
- Requirements: Safety (only one holder at a time), Liveness (eventually acquire if no holder), fault tolerance, avoid deadlocks.
- System Model: Distributed environment, unreliable networks, nodes/processes can fail, partial synchrony maybe.
- High-level Design:
- Lock Service: cluster of nodes using consensus (Raft) to maintain lock state.
- Lock state: holder (client ID), fencing token (monotonic), expiration time (if lease).
- API: acquire(lock_name, lease_time) -> (success, fencing_token, expiration) or fail; release(lock_name, fencing_token); renew(lock_name, fencing_token, new_lease).
- Clients: must provide fencing_token when accessing protected resource; resource checks token validity (or just assume lock service ensures exclusive access? Actually fencing tokens are used by resource itself to detect stale operations. Typically lock service issues fencing token to client, which then includes it in each operation on the resource. The resource (e.g., a database) maintains the highest token seen and rejects lower ones.)
- Fencing Tokens:
- Why needed: To prevent a client that held the lock but crashed/partitioned and later recovers, from performing operations after losing the lock due to TTL expiration or another client acquiring.
- Mechanism: When lock is granted, lock service returns a unique, monotonically increasing token (e.g., 64-bit number). The client must present this token when accessing the protected resource. The resource maintains the highest token it has seen. If a request arrives with a token lower than the current, it's rejected. This ensures that only the most recent lock holder can make changes. Tokens should be globally unique and ordered.
- Implementation: Fencing token can be a combination of (server epoch, counter) or simply a per-lock counter that increments on each grant. Since lock service is replicated via Raft, it can generate a monotonic sequence.
- TTL (Time-to-Live):
- Each lock has a lease duration (TTL). When acquired, the lock is valid for that period. Client must renew (extend) before expiry to keep holding.
- TTL ensures that if a client crashes or loses network, the lock will eventually be released automatically.
- The lock service tracks expiration times; when a lease expires, lock becomes free.
- Renewal: client calls renew with same fencing token; if token matches current and not expired, lease extended.
- TTL is based on server's clock; clients request a duration, server sets absolute expiration. Prevents client clock manipulation.
- Failure Modes and Handling:
- Client crash after acquiring lock: TTL expires, lock released. Fencing token becomes invalid; any in-flight operations with old token may be accepted if they arrive before TTL expiry? Actually resource checks token against highest seen. If new client acquires later with higher token, resource will reject old token because it's lower than current. But if old client's operation arrives after its lock expired but before new lock acquired, it might still be highest seen? Resource state: if lock expired without a new holder, resource still has old token as highest? That could allow old operations to succeed after expiration, but that's okay? Actually after lock is released, we want no client to have exclusive access; but if old client sends operation with token that was valid when they held lock but after lock release, should it be allowed? No, because mutual exclusion: after lock is released, any client should be able to acquire. But if old client's operation arrives after its lock expired but before new acquisition, it would still be the highest token seen, so resource would accept, violating mutual exclusion because there is no guarantee that another client didn't also get the lock in that window? Actually the window after expiration and before new acquisition is a period when no client holds the lock. But if an old operation is processed, it's effectively as if the client still has the lock. That could be okay if we consider that the lock service may not have revoked the token; but the client should not be allowed to operate after its lease expired. The resource must reject operations whose token is not currently associated with the lock holder. So resource needs to know current lock holder's token. It could query lock service on each operation, but that's heavy. Alternatively, the resource can maintain a local state: if token equals current token, accept; else reject. But what about after expiration? The lock service removes the lock, so current token is none. The resource should then reject any token. So resource must be aware of lock state changes. However, fencing token design typically uses an ever-increasing token; the resource just remembers the highest token it has ever seen, and rejects any token lower than that. This doesn't require knowing current lock state. But after lock expires, the next client gets a higher token. The old token is lower, so it will be rejected. But if the lock expires and no one else has acquired yet, the highest token is still the old one. Then if old client sends operation, token equals highest, it would be accepted. That's a problem. However, typical fencing token usage includes a "generation" or "epoch" from lock service. But the resource doesn't know about expiration. So to avoid this, the lock service could issue tokens that include a lease expiration? Not straightforward. Actually typical fencing token schemes for distributed locks (like in Chubby, Zookeeper) use a handle (lock token) that is verified by the lock service before performing operations on the resource. That is, the client presents token to lock service to perform operation, not directly to resource. That's more of a lease. But many designs separate lock service from resource: lock service issues token; resource checks token. The common solution is to have the resource maintain a "lock state" that includes the token and a "valid until" time. Or rely on the fact that once a lock is granted, the client is expected to perform work promptly; after TTL, the lock is considered released; any operations after that with the token should be considered invalid. So the resource should reject tokens whose lease has expired. The resource would need to know the lease expiration. That couples resource to lock service. Alternatively, the lock service can be used as a proxy for all operations: clients do lock.acquire() and then lock.execute(operation). That's not typical.
Better approach: The lock service itself can be used as a fencing token service: The token is just a unique identifier; the protected resource (e.g., a database) must implement fencing by storing the token of the current owner and only accepting operations from that token. The lock service notifies the resource of token changes? That adds complexity.
Simpler: We design the lock service to be used in conjunction with a resource that checks the token. The token is just a unique, increasing number. For each lock name, the resource stores the maximum token it has seen. If a request comes with a token equal to the current max, it's accepted, and the token is updated? Actually it should only accept if token equals the current max, because when a new client acquires the lock, the token increases and becomes new max. The old client's token is less than new max, so it's rejected. However, after the lock expires and before a new client acquires, the max token remains the old one. So an operation with that token would be accepted. To avoid that, we need to reset the max token when lock expires. But the resource doesn't know when lock expires. So we need an additional mechanism: lock service could send a "revoke" or "release" event to resource? That adds complexity. Or we could design the token to include a generation number that increments each time the lock is granted, and the resource also stores the generation. When the lock expires, the resource should invalidate its state. How does it know? Possibly the resource periodically checks with lock service? That defeats the purpose.
Thus, typical fencing token approach in the literature: Use a monotonic counter that is incremented on each handover of the lock. The resource remembers the last token it saw. As long as the token is increasing, only the latest holder will succeed. But the scenario where lock expires and no new holder: the resource's last token is still old, and a client might still present that token and be accepted. However, if the client is still alive and its lease expired, it should not be allowed to operate. But could it be that after lease expiration, the client should have stopped using the token? It might still try. So we need to ensure that after expiration, token is invalid. So the token itself must embed expiration or be tied to a lease that the resource can check. Maybe the lock service returns token + expiration time, and the resource checks that current time < expiration. But that requires synchronized clocks.
Alternate pattern: The lock service is used for mutual exclusion by providing a lease; the client never directly accesses the resource with the token. Instead, the lock service provides a lease, and the client then performs its operation on the resource under the assumption that it holds the lease; the resource does not check tokens. That is dangerous because a client might operate when it lost the lease due to network partition. So fencing is needed: the resource must be able to reject operations from a client that no longer holds the lease. So the token must be verifiable by the resource without contacting lock service. That is challenging if we want to also handle expiration. But maybe we can relax: the token is just a unique ID; the resource stores the token of the current owner. The lock service, upon granting the lock, also informs the resource (or the resource reads the current lock holder from the lock service) to update its token. That would require the resource to be aware of lock service state. But if the resource can't talk to lock service, it's not fencing.
Actually, the classic "fencing token" in distributed systems is used in protocols like Paxos to prevent old leaders from conflicting. In that context, each proposal has a monotonic number, and acceptors reject proposals with lower numbers. That works because acceptors keep the highest number they've seen. Similarly, for a lock, we can treat each client operation as a "proposal" to access the resource, with a fencing token. The resource (the acceptors) will accept only if the token is higher than any seen before. But then after a client loses the lock, it may still have a token that is higher than any seen before? No, because the next client will get a higher token, so old token will be lower. But if the lock expires and no new client appears, the token remains highest. However, if no client holds the lock, we want no operations to be accepted. But the highest token seen is still the last client's token. So any operation with that token would be accepted. That means that after lock expires, the resource is still in a state where it accepts that token. So we need a way to invalidate the token after expiration. Perhaps the token includes a lease expiration time, and the resource checks that the current time is before expiration. But then we need synchronized clocks. Could use the lock service's time; token could be signed with expiration. The resource can verify signature? That might be heavy.
Alternate: Instead of using fencing token for resource access control, we can use the lock service itself to mediate all access: the client must first acquire a lease to perform an operation. The operation request goes to the lock service, which checks if the client holds the current lease and then forwards the operation to the resource. That's like a master. That defeats the purpose of having a separate lock service? Actually that's a common design: a distributed lock manager that also acts as a gatekeeper. For example, in Chubby, clients use the lock to gain exclusive access to a file; they then read/write the file directly, but the lock service ensures only one client has the lock at a time. But wait, in Chubby, after acquiring a lock, the client can read/write the file directly on the Chubby server? Actually Chubby is a lock service that also provides a file system API; it's a centralized service that handles both locking and storage. But in a typical lock service, the lock is separate from the resource. Clients are expected to respect the lock and only access the resource while holding the lock. There's no enforcement. That's why fencing tokens are used to enforce that only the lock holder can access the resource, by having the resource check the token.
But as argued, the token alone is insufficient for expiration. However, maybe the assumption is that the lock holder will not access the resource after its lease expires because it knows its lease is over. But if the client is partitioned or buggy, it might still try. So we need protection. We could have the token include an expiration timestamp that the resource can check. That requires synchronized clocks, but we can rely on the lock service's time (which is consistent across servers) and have the resource trust the lock service's timestamp? The resource can get the time from the lock service when token is minted? But the token would be a data structure: {token_id, lease_expiration, signature}. The resource can verify the signature (using a public key of lock service) and check expiration. That would work without contacting lock service. But it adds cryptographic overhead.
Alternatively, we can design the system such that the lock service is the only one that can grant access to the resource; i.e., the resource does not accept any operations unless accompanied by a valid lease, which is verified by the lock service via a fast RPC. That is like a token that the resource can validate by checking with lock service (online). That introduces a dependency but could be cached.
Given the question is about designing a distributed lock service, not necessarily the resource's enforcement mechanism, we can discuss fencing tokens as a mechanism for the resource to protect itself, and discuss how to handle expiration. We might say that the fencing token is accompanied by an expiration time, and the resource checks both token and expiration. Or we could say that the lock service notifies the resource when a lock is granted or released (via a callback or by the resource subscribing). But that's heavy.
Maybe there's a known design: "Fencing tokens" are typically used in conjunction with leases. The lock service issues a lease with an expiration time; the token is the lease identifier. The resource, to accept an operation, requires that the lease is still valid (by checking expiration) and that the token matches the current lease. But the resource doesn't know current lease unless it's synchronized. So typically, the lock service and the resource are integrated: the lock is part of the resource management. Or we can assume the resource is a replicated state machine that also uses the same consensus protocol? That's too much.
Simplify: We'll design the lock service that maintains the lock state and also provides a way for clients to safely access the resource. The service could provide an "execute" operation: client calls lock.execute(lock_name, operation) and the lock service, if the client holds the lock, forwards the operation to the resource. This centralizes enforcement. But then the lock service is a bottleneck.
But in many distributed lock systems like etcd or ZooKeeper, the lock is a node in a hierarchical data store; clients acquire lock by creating an ephemeral sequential node. The lock is held by the client with the smallest node. To prevent stale clients, they use sequential nodes and monitor them. They also use session timeouts (TTL) for the client connection. Fencing is not typically provided; it's up to the application to use version numbers. But there is a concept of "fencing" in ZooKeeper using version numbers on znodes? Actually ZooKeeper's atomic broadcast ensures linearizable operations; once a lock is released, the data changes. But the client may still try to update data after losing lock; ZooKeeper's update can include a version number (expected version) to prevent stale writes. That's like a CAS. That's a form of fencing: the lock service provides a version number (or node sequence) that increments each time lock is granted; the client uses that version as expected version when updating the resource (which is stored in ZooKeeper). So the resource is stored in the same ZooKeeper ensemble, so the lock service and resource are collocated. That's a common pattern.
Thus, for our design, we can assume the protected resource is stored in the same replicated store (or the lock service itself can act as a storage for fencing tokens). The lock service can store the current fencing token for each lock in its replicated log. The resource (maybe a separate service) can query the lock service to get the current token for the lock before performing an operation, or the lock service can directly validate.
Alternatively, we can separate concerns: The lock service maintains lock state, and the resource maintains its own fencing token. The lock service, when granting a lock, also sends the new token to the resource (e.g., via a callback). That's similar to "fencing" in HDFS JournalNode: the active NN sends its epoch; standby rejects older epochs.
Given the question, we need to cover the three concepts: fencing tokens, TTLs, and failure modes. So we can present a design that uses fencing tokens to prevent old clients from accessing resource after they lose lock, TTL to auto-release locks, and discuss failure modes (client crash, network partition, server failure, clock skew) and how they're mitigated.
Perhaps we can structure the answer as:
- Overview: A distributed lock service provides mutual exclusion for resources across nodes. We'll design using a replicated state machine for safety.
- Core data structures per lock: holder (client ID), fencing token (monotonic), lease expiration (timestamp).
- API: acquire(lock, leaseDuration), release(lock, token), renew(lock, token, leaseDuration).
- Fencing tokens: generated by the lock service as a strictly increasing number per lock. When a client acquires a lock, it receives the current token. When the client accesses the protected resource, it must present that token. The resource will only accept operations if the token matches the latest token it has stored (or greater). The resource can store the token from the last successful operation or from the lock service's current state. We'll elaborate: The resource can maintain a variable "current_token" which is updated when the lock service notifies it (or when the client passes the token and the resource checks with lock service). Simpler: the lock service itself acts as the authority: the resource stores the token as part of its state, and changes to the resource require that the token matches the current lock's token; because the lock service updates the lock token under consensus, the resource's state is also part of the consensus if it's integrated. But let's keep it decoupled: The resource can check the token by performing a read of the lock state (with caching) from the lock service. But that's a read. Instead, we can have the lock service provide a "fencing token" that includes a lease expiration and is signed, so the resource can verify offline. That's robust.
Given time, we might skip deep integration and say: "The fencing token is a unique, monotonically increasing identifier issued by the lock service. The protected resource maintains the highest fencing token it has seen for that resource. Any operation with a token lower than the current highest is rejected. This ensures that only the latest lock holder can make changes. Additionally, the token includes an expiration time (or the resource also checks TTL) to prevent use after lease expiration." Then discuss that the resource must also handle expiration: either by having the lock service push revocation events or by having the token include an expiry and checking system time.
To avoid clock issues, we could say that the lock service's time is used; the token includes an absolute expiration time; the resource trusts the lock service's time and only accepts tokens whose expiration is in the future and which are >= current token.
Alternatively, we can design that after lease expiration, the lock service will clear the lock and the fencing token becomes invalid; the resource, upon receiving an operation with a token, can query the lock service (or a sharded cache) to see if that token is still the current one. This is a fast check (local read from a quorum?). But still network.
Maybe it's acceptable to have the resource check with lock service each time. For high performance, it might not be ideal, but for design we can mention caching with short TTL.
But the question likely expects a high-level design, not an implementation detail. So we can state: "The fencing token is a unique, ever-increasing number associated with the lock lease. The protected resource must verify that the token presented is greater than or equal to the token it has on record (which is the token of the last successful operation). This ensures that any stale operation from a previous lease holder will be rejected because its token is smaller. To handle the case where a lock expires without a new acquisition, the resource could also invalidate its stored token after a local timeout or after receiving a release notification from the lock service." But that's messy.
Better: Use the approach from "Leases" by Gray: The lock service grants a lease with an expiration time. The client must renew. The fencing token can be the lease identifier. The resource includes the lease identifier in its state. When the lease expires, the lock service marks the lease as expired, and any operations with that lease are rejected because the resource can check with the lock service or the lock service will have revoked it. But again, we need a way to propagate revocation.
Let's step back: In the classic "distributed lock with fencing" design (like in the book "Designing Data-Intensive Applications"), they talk about using a monotonic token to prevent split-brain. They often describe a scenario where a lock service like ZooKeeper provides a sequential znode; the sequence number is the fencing token. The client uses that number to update the resource (e.g., a database row) with a conditional update that checks the version number. If the resource stores a version, the client must increment it using the token as new version. But the version is stored in the resource's state. The resource (e.g., a database) uses optimistic concurrency control: each write includes an expected version, and the version is set to the token. The database rejects writes where the version doesn't match the current version. Since the token is strictly increasing, only the latest lock holder can succeed. That's a clean separation: the lock service and the resource are separate; the resource uses Compare-and-Set based on the token. For example, a row in a database has a column 'lock_token'. The client reads it (gets current token), then on update sets it to its own token with condition that current token equals read value. But if the token is strictly increasing, you could simply set it unconditionally? No, you need to ensure that you are not overwriting a newer token. Actually if the resource has a token column, the client must read it first to know what it is. Then when performing its operation, it can set the token to its token and also perform other changes, but the update must be conditional: WHERE token = old_token. This ensures that if another client acquired later with a higher token, the old token will be smaller and the condition fails. That's a standard technique. It doesn't require the resource to know about TTL directly; the lock service ensures that after lease expiration, the token is no longer valid because the next acquisition will have a higher token. However, what about the period after lease expiration and before new acquisition? The token still exists in the resource; any client that still has the old token could write if it can guess the old token? But the condition will check that current token equals the old token; if no other client has changed it, it will still equal the old token, so the operation would succeed. That is a problem because the client's lease has expired, but it still holds the token and the token is still the current token. So we need to have the lock service actively revoke the token upon lease expiration. That could be done by having the lock service notify the resource to clear the token or increment it. But perhaps the assumption is that once a lease expires, the client is supposed to stop accessing the resource; but if it does, it's a violation. The risk is that after lease expiration, the client might still be the only one that knows the token and could perform an operation, effectively extending its exclusive access beyond lease. That could be a liveness issue or safety? Actually safety: mutual exclusion might be violated if a stale client writes after its lease expired but before a new client acquires the lock. But during that window, no other client is supposed to access because the lock is free; but if the stale client writes, it's still exclusive but that's okay? Exclusive means only one client at a time. The stale client is the only one writing, so exclusivity is not violated. However, the lock is supposed to be held only for the lease duration. The client is overstaying, but exclusivity is still maintained. That might be acceptable if we only care about mutual exclusion, not about enforcing maximum lease times. But the lease is there to prevent indefinite lock holding due to client crash. If the client is alive but partition such that it didn't receive lock release but its lease expired, it might still think it holds the lock and continue working. That could cause the lock to be held longer than intended, but as long as no other client tries to acquire, it's not a correctness violation of mutual exclusion (since no other client is contending). However, if the client is alive but has network partition that prevents it from renewing but it still can access the resource, and then another client (which got the lock after expiration) also accesses the resource? That would be a violation. That's the scenario we need to prevent: two active clients at the same time. So we need to ensure that when a lease expires, the lock is considered released, and a new client can acquire. But the old client may still try to access. To prevent concurrent access, the resource must reject the old client's operations once a new client has acquired with a higher token. That's where fencing token helps: the new client gets a higher token; when it updates the resource, it will set the token to the new value (or maybe just use CAS). The old client's subsequent operation would have the old token; if it tries to write, it would fail because the token in resource is now higher. But what if the old client writes before the new client acquires? That's before the new client tries to write, so there is no conflict because no other client is active. That's okay? That would mean the old client extended its exclusive access beyond its lease without interference, but that may be against policy but not breaking mutual exclusion. However, if the old client's lease expired, it's supposed to release the lock. But if it continues to operate, it may starve others. That's a liveness issue: progress might be hindered. But we cannot prevent a crashed client from continuing to operate if it's still alive but thought it had lease; but we can at least ensure that once a new client acquires, it can take over. So the critical thing is to avoid two concurrent active clients. The scenario where old client continues after lease expiry but before new client tries to acquire leads to a window where the lock is not free but considered free by lock service. That could cause new client to think it acquired and start operating, leading to concurrency. To avoid that, we need a way for the resource to know that the lease has expired independently of token. That is tricky without a revocation mechanism. Many systems rely on the fact that leases are relatively short and that clients will detect expiration (by trying to renew) and stop. But if a client is partitioned, it may not detect expiration and may continue. To protect, we need strong fencing: the lock service must somehow invalidate the token upon lease expiration. One way is to have the lock service periodically broadcast the current token to the resource, or have the resource poll. But in practice, many systems use a separate lease mechanism: the resource does not rely on token; instead, the lock service itself mediates access: the client must call lock.execute which checks lease and then performs operation. That avoids the need for the resource to check expiration.
Thus, in our design, we might propose that the lock service is the sole access point to the resource. But that could be a performance bottleneck. Alternatively, we can combine: The lock service issues a lease and a fencing token. The resource checks that the token is at least as high as a known safe value. The lock service, upon granting a new lease, increments a counter and writes that to the resource (e.g., via a write-ahead log) before considering the lock granted. That way, the resource's token is always the latest granted. But then the resource needs to be replicated or reachable.
Better to keep it simple: The lock service and the resource are separate, but the resource uses a compare-and-swap operation that includes the fencing token as the expected version. The lock service ensures that each time the lock is granted, it assigns a new token that is strictly greater than any previously issued token (including expired ones). The resource stores the latest token it accepted. For an operation, the client sends its token and the operation with a CAS: it will only succeed if the current token at resource equals the token that was present when the client last successfully performed an operation? That seems messy.
Actually, a standard pattern: The resource has a field "last_lock_epoch". The client that holds the lock knows the epoch (fencing token). When it wants to perform an action, it writes the epoch along with its changes, but only if the current epoch at the resource is equal to the epoch it read earlier. But if the epoch is increasing, the condition is that the resource's current epoch equals the client's epoch. Since epochs only increase, once a new lock is granted, the epoch at resource will be updated to that new epoch (by the new lock holder's first operation). Then old clients cannot write because the epoch will be higher than theirs. However, this requires the resource to store the epoch and for operations to include the epoch as a condition. That's exactly CAS: update where epoch = old_epoch. The client must first read the current epoch to know what old_epoch to use. But that read could be stale; it's a classic race. Actually, the condition is that the operation should only succeed if the resource's epoch is still equal to the client's token. That's like a conditional update based on version. The client does not need to read first; it can include its token as the expected version. The update will succeed only if the stored version equals that token. If the token is less than the current version (because a newer token was set by a later client), the update fails. That's exactly how compare-and-swap works: you specify the old value you expect; the system checks that the current value matches that old value; if not, reject.
So the resource must keep a version number. Initially, maybe null. When a client acquires the lock, it gets token T. The resource's version is maybe X. The client attempts to perform its operation with condition: version = T? But the resource's version may not be T yet. Actually, the resource's version should be the token of the current lock holder. So we need to set the resource's version to T when the lock is granted. How does the resource learn about the new token? The lock service could write it to the resource as part of the lock acquisition protocol, or the client could set it as part of its first operation. Let's think: In many designs, the lock service does not directly update the resource; instead, the client, after acquiring the lock, performs its operation on the resource, and that operation includes the token as a version. If the resource's current version is less than the token, the operation could succeed and set the version to the token. But if the resource's version is already higher (from a newer lock holder), then the operation fails. However, what about the initial state? The resource version might be null. A client with token T could perform an operation with condition: version is null or less than T? To ensure only the lock holder can write, we could require that the operation includes the token and that the token must be greater than or equal to the current version? Not safe. Better: The resource enforces that the token in the operation must equal the version that was set by the previous successful operation of the current lock holder. That's a loop.
Actually, the typical fencing token technique uses a "generation number" that is monotonically increasing and the resource stores the highest generation number it has seen. Any operation with a generation number lower than the stored highest is rejected. The generation number is set by the lock service each time the lock is granted. But how does the resource's stored highest number get updated? It is updated by each operation that arrives; when an operation with generation G is processed, if G >= current stored G, then it's accepted and stored G becomes G. But if a new lock holder with higher G arrives, its operation will update the stored G to that higher G. An old client with lower G will be rejected because its G is less than stored G. That's exactly the idea: The resource simply remembers the highest generation number it has ever seen. It doesn't need to know about lock state directly. But the problem of expiration: after a lease expires, there may be no client with a higher G to update the stored G. The stored G remains at the old value. Then if the old client (with G) operates after expiration, it will be accepted because G equals stored G. That's the issue. However, note that after the lease expires, the old client should no longer be allowed to operate. But if it does, it will succeed because the stored G hasn't changed. So we need a way to force the stored G to become higher than the old G after expiration, even without a new client acquiring. One approach: The lock service, upon lease expiration, could increment a global epoch or something and write that to the resource. But that requires the lock service to be able to update the resource. That's an extra step. Or the resource could have a local timer: if the last operation from a client with token G was more than X ago, it resets the stored G to something lower? That doesn't help because resetting lower would allow old G to be accepted again.
Alternatively, we can design the fencing token to include a time component and have the resource reject tokens that are too old based on its local time? That's clock sync again.
Maybe we can accept that after lease expiration, if the old client continues to operate without being challenged, it's not a safety violation because no other client is trying to acquire; but if a new client attempts to acquire, it will get a new token G' > G, and will try to perform its operation with G'. The resource will see G' > stored G and accept, updating stored G to G'. Then any subsequent operation from old client with G will be rejected. However, there is a window between lease expiration and new client's first operation where the old client might still operate. But if the new client attempts to acquire, it will succeed because lock service grants it (since lease expired). It then attempts to do work with G'. But what if the old client is still operating in that window before the new client's first operation? The old client could perform operations that change the resource's state, and the new client will later read that state. That's allowed because the old client was the only one during that window; it's as if the lease was extended. That may be acceptable? But the lock service considers the lock available, so the new client may think it's safe to start operating. If the old client is still active and performs some writes after the new client starts but before the new client writes, they could interleave. Actually, the new client might first read the state, then write. If the old client wrote after the new client read but before it wrote, the new client's write might overwrite based on CAS condition using its token. Let's simulate: Lock expires at time T_exp. Old client still alive, may attempt writes. At time T_new > T_exp, new client acquires lock, gets token G_new > G_old. New client reads resource state (maybe reads some data). Meanwhile old client writes some data using its token G_old. Then new client writes using token G_new with condition that resource's version equals something? The new client doesn't know about G_old because it never read version? Actually, for the new client to safely apply its changes, it must ensure that the resource's state hasn't changed by a stale client. The CAS condition would be something like: "set version = G_new only if current version = G_old?" No, that would fail because current version is still G_old (if old client hasn't written yet) or G_old after its last write. But if old client wrote after new client read but before new client writes, the resource version might still be G_old (if old client's write succeeded and updated version to G_old again? It would still be G_old). New client's write with condition version = ??? Actually, new client's operation should set version to G_new. The condition could be that the current version is either G_old or less than G_new? Typically, we require that the operation succeeds only if the version is exactly the token that the client presents? That would fail because the current version is G_old, not G_new. So the new client must first elevate the version to G_new. How does it do that? It could perform an update that sets version = G_new unconditionally? But that would allow any client to set version. So the typical pattern: The lock service, when granting the lock, also writes the new token to the resource as part of the lock acquisition, before acknowledging the client. That ensures that the resource's stored token is updated to the new value before the client starts operating. Then the client knows that the resource's token is set to its token. Then subsequent operations by the client can require that the token matches its token (or be part of the operation). If the lock service updates the resource's token upon grant, then after lease expiration, the token remains at the last granted value (maybe the old one if no new grant). But if the lease expires and no new grant, the token stays at old value. That means old client could still operate and set token to its own value (which is old), but that's fine because it's still the same token. But if a new client acquires after expiration, the lock service will update the resource's token to the new token before granting. That update will set token to a higher value. The old client's subsequent operations with lower token will be rejected if they check that token >= current? Actually if the operation expects token = its token, it will fail because current token is higher. So that works! So the solution is: The lock service, as part of acquiring the lock, must write the new fencing token to the resource (or to some shared state) before returning success to the client. That ensures that the resource's token is always the most recently granted token. Then old clients cannot operate after a new grant because their token is lower than the resource's token.
Thus, we need to integrate the lock service with the resource to some extent. But that's common: the lock service can be a separate service that also updates a field in the resource (like a "lease" field). For example, in a database row, there could be a column 'lock_token'. When the lock service grants a lock, it performs an atomic update to set that column to the new token, perhaps using a compare-and-swap with condition that the current token is less than new token? Actually, the lock service itself must do this update atomically as part of the lock acquisition algorithm, using consensus. But if the resource is external, the lock service can't atomically update it along with its internal state. So we need a two-phase commit? That's heavy.
Alternatively, the lock service can be designed such that the token is stored within the lock service, and the resource simply checks with the lock service on each operation whether the token is still valid. That's a network call but can be cached. That might be simpler: The resource maintains a cache of the current token for each lock, and refreshes it periodically from the lock service. But then the race condition remains if the cache is stale.
Given the complexity, for an interview design answer, we might simplify by saying: The lock service maintains the lock state, and the resource is protected by requiring a fencing token that must match the current token stored in the lock service. The client includes the token in its request to the resource. The resource then makes a fast RPC to the lock service to validate the token (is it still the current token for that lock?). This adds latency but ensures correctness. The lock service can answer quickly because it has the current state (maybe in memory). This is similar to using a token that is checked by the resource by contacting the authority. TTL ensures that tokens expire after lease duration; the lock service removes them. So after expiration, the token is no longer valid. The resource will see invalid and reject. This avoids clock issues because the lock service knows the expiration.
But that makes the resource depend on lock service; if lock service is down, resource can't validate. Could use a cached token with a short TTL and a grace period. That's similar to microservices auth.
Given the question is about designing a distributed lock service, we could keep the resource validation as a separate concern. We need to focus on lock service design.
So I'll propose a design where the lock service is a replicated state machine (using Raft). It maintains for each lock:
- lock_name
- holder (client ID, maybe connection ID)
- fencing_token (monotonic integer)
- lease_expiration (timestamp)
Clients communicate with the lock service to acquire, release, renew. The service ensures that at most one holder exists at any time because the state machine processes operations sequentially and enforces that a lock can be held by only one client.
Fencing token: When granting a lock, the service generates a new fencing token (e.g., incrementing counter per lock). This token is returned to the client. The client must present this token to the protected resource when performing operations. The resource will accept an operation only if the token matches the current token for that lock, which it can get from the lock service (via a query or via a push). To avoid extra RPC, we could have the lock service also expose the current token via a read-only endpoint that the resource can query. But we can say the resource is expected to check with the lock service or to have the token embedded in the operation and the lock service can validate during the operation if the resource is part of the lock service (like a storage service). Maybe we treat the lock service as also providing a key-value store where the resource is stored. That's like etcd.
Alternatively, we could adopt the design of etcd: locks are built on top of a compare-and-swap key-value store. The lock is represented by a key; clients try to acquire by creating a key with a unique value and a lease. The smallest key (by revision) holds the lock. The fencing token is the revision number. The resource (another key) can be updated conditionally on the lock key's revision? That's integrated.
But the question doesn't require us to design the resource; only the lock service. So we can describe the lock service API and the properties, and we can mention that the fencing token is used by the client to perform safe operations on the resource, and we can explain how it prevents stale operations even in presence of failures, including TTL.
Thus, in the answer, we can outline:
- System: a cluster of lock servers using Raft. All lock state stored in Raft log. Servers expose gRPC/HTTP.
- Lock name is a string.
- Acquire request includes client ID, desired lease duration (TTL). The lock server, if lock is free or current holder has expired, creates a new lock entry with:
- holder = client ID
- fencing_token = next_monotonic_number()
- lease_expiration = now + lease_duration
- returns AcquireResponse with fencing_token and lease_expiration.
- If lock is held by someone else with a non-expired lease, request fails (or blocks? We can support blocking or non-blocking. We'll say non-blocking for simplicity; blocking can be implemented via watches).
- Renew request: client sends token; server checks token matches current holder and extends expiration.
- Release request: client sends token; server verifies token matches current holder, then clears lock.
- Failure handling:
- Server crash: Raft ensures state replicated, so failover.
- Network partition: If majority partition, lock service continues; minority cannot make progress. Clients in minority cannot acquire or release, but their existing locks may expire.
- Client crash: lock lease expires, server automatically releases when expiration passes.
- Client fails to renew: lease expires.
- Clock skew: TTL based on server time, not client's. Acquire returns expiration; client can compute remaining time.
- Lost messages: idempotent operations, clients retry.
- Fencing token details: The token is globally unique and strictly increasing per lock. It is used by the client to prove it currently holds the lock. The resource should only accept operations with a token that is at least as high as the last seen token. Because the token always increases, this ensures that after a new token is issued, any operation with an older token will be rejected. To handle the case where a lock expires without a new acquisition, we rely on the fact that the token remains the same; a client with that token could still operate, but since no other client is contending, safety (mutual exclusion) holds. However, liveness (fairness) might be affected; but we can mitigate by having the lease expire and the client voluntarily stop using the token. The token's validity is tied to the lease expiration; after expiration, the token should be considered invalid by the resource. The resource can enforce this by checking the expiration time (which can be included in the token or fetched from lock service). We'll include expiration in the token: token could be a struct {value, expires_at} signed by lock service. Resource verifies signature and that expires_at > now (using its own clock, but that's okay if clocks are reasonably synchronized; we assume NTP). Alternatively, resource can call lock service to validate token.
We'll choose the approach where the lock service stores the token and expiration, and the resource checks with lock service on each operation (or caches). For simplicity: "The resource can validate a token by querying the lock service to see if the token is still current (i.e., matches the current fencing token for that lock and is not expired). This check is fast and can be cached for a short duration."
But maybe better: "The lock service, upon granting a lock, also writes the fencing token to a globally visible location (e.g., a distributed key-value store) that the resource watches. The resource then knows the current token."
Given the scope, we can ignore the resource validation details and just say: "The fencing token is used by the client to demonstrate current ownership. The protected resource must verify that the token equals the latest issued token (or is greater than any previously seen). The lock service ensures tokens are monotonic, so any token presented after a newer token has been issued will be rejected."
We should also mention that fences can be used by the resource to prevent operations from a client that lost the lock due to network partition. For example, if client A holds the lock and then gets partitioned, its lease may expire, and client B acquires the lock with a higher token. If client A recovers and tries to operate, its token is lower and will be rejected.
Now, failure modes:
-
Client failure: Handled by TTL; lock automatically expires. However, if the client had a long lease and crashes, the lock may be held until TTL expires; this is a window of unavailability. TTL should be chosen appropriately.
-
Network partition among clients: Two clients in different partitions may try to acquire the same lock. The lock service cluster ensures linearizable updates, so only one will succeed because only one partition can have a majority to commit. The minority partition will not be able to acquire; they might time out or get errors. That's safe.
-
Network partition affecting lock service itself: If the Raft cluster loses majority, it becomes unavailable. No locks can be granted or released until a majority is restored. Existing locks may expire due to TTL, but no new grants. That's acceptable.
-
Clock skew: If clients have skewed clocks, they might misinterpret TTL. But TTL is server-side; client only gets expiration timestamp. If client's clock is behind, it might think lease is still valid when it's actually expired; but it will try to operate and resource will see token expired. So client should not rely on its own clock for validity; it should treat server's expiration as authoritative.
-
Slow client: If client delays renewing due to GC pause, lease may expire and it might lose lock. That's by design (leases are not forever). So clients must renew frequently enough.
-
Concurrent acquire attempts: Raft serializes; one succeeds, others fail.
-
Server failure while processing acquire: Raft ensures only committed entries are applied; if leader fails before commit, no lock state change; if after commit but before response, client may retry; operation is idempotent because token generation is idempotent? Actually, if client didn't get response, it can't know if lock was acquired. It can query or attempt acquire again with a new request; the lock service must be safe with duplicate requests. We can include a unique request ID to deduplicate.
-
Duplicate release: Release must be idempotent; token once matched, lock cleared; subsequent release with same token should be no-op.
We should also consider the scenario where a client holds the lock and then its network connection to lock service is lost, but it still has token. It might not be able to renew; its lease will expire. Meanwhile, it might continue to operate on the resource. But if a new client acquires, token will be higher, and new client's operations will succeed; old client's operations will be rejected because token lower. So safety holds.
Now, let's write the answer in a clear, structured manner. We'll include:
- Introduction: purpose and constraints.
- System architecture: Raft cluster, clients.
- Data model: Lock entry.
- Operations: Acquire, Renew, Release. Include details on token generation, TTL.
- Fencing token: explanation, how it's used, generation.
- TTL: lease mechanism, expiration handling, renewal.
- Failure modes: discuss various failures and mitigation.
- Additional considerations: fairness, blocking waits, scalability.
We need to be concise but comprehensive.
Let's produce final answer.
Distributed Lock Service Design
1. Goals and Assumptions
- Provide mutual exclusion (safety: at most one holder per lock) and progress (liveness: eventually grant the lock if it becomes free).
- Operate in an asynchronous network with possible node failures (crash‑stop), message loss, and reordering.
- Use a lease (TTL) to avoid deadlocks due to crashed clients.
- Issue fencing tokens so that a stale holder cannot corrupt the protected resource after losing the lock.
- Build on a replicated state machine (Raft/Paxos) for strong consistency.
2. System Architecture
- Lock servers: a Raft cluster (odd number of nodes). The Raft log stores all lock state changes. The elected leader processes client requests; followers replicate the log.
- Clients: any process that needs exclusive access to a named resource. They communicate with the leader (or any server, which forwards).
- Protected resource: external storage (database, file, etc.). It is not part of the lock service but must cooperate by checking fencing tokens.
3. Lock State (per lock name)
struct Lock {
holder: ClientID? // null if free
fencing_token: uint64 // strictly increasing per lock
lease_expires: Timestamp // server time when lease ends
}
fencing_token is a monotonically increasing counter (per lock) generated by the leader on each grant.
lease_expires is set to now + lease_duration when the lock is granted or renewed.
4. API
All operations are linearizable; the leader serializes them via Raft.
5. Fencing Tokens
- What: A unique, ever‑increasing number assigned to each lock grant.
- Why: Prevent a client that lost the lock (e.g., due to network partition, lease expiry) from performing operations on the protected resource after a newer holder has appeared.
- Usage by the resource:
- The resource stores the highest fencing token it has ever accepted for that resource (call it
current_token).
- Every operation on the resource must carry the client’s fencing token
T.
- The resource accepts the operation only if
T >= current_token. If accepted, it updates current_token = T.
- Because tokens are strictly increasing, any stale holder with an older token will be rejected once a newer token has been recorded.
- Enforcement:
- The resource can check the token directly (as above) and optionally verify that the token is still valid (i.e., the corresponding lock has not expired) by making a fast RPC to the lock service (or using a short‑lived cache). This prevents a client from using an unexpired token after its lease ends but before any newer token arrives.
- The lock service, when granting a lock, may also proactively push the new token to the resource (e.g., via a watch/notification) to keep
current_token up‑to‑date.
6. Time‑to‑Live (Leases)
- Each lock has an expiration time (
lease_expires). The lock is automatically considered free when now >= lease_expires.
- Automatic release: The lock service checks expiration on each Acquire/Renew/Release request and also in the background (or lazily) to treat expired locks as free. No explicit action from the client is needed.
- Renewal: Clients must periodically renew (e.g., before
lease_expires - safety_margin) to keep the lock.
- TTL choice: Should be long enough for normal operation but short enough to bound the time a crashed client holds the lock.
- Clock handling: All timestamps are server‑side. The client receives an absolute
lease_expires value; it does not rely on its own clock.
7. Failure Modes and Mitigations
| Failure Scenario | Effect & Handling |
|---|
| Client crash | Lease expires → lock becomes free. No resource damage because any later operation with the stale token will be rejected by the resource (token lower than current_token after a new grant, or expiration check). |
| Client network partition | Client cannot renew → lease expires. Other clients can acquire. Stale client’s future operations are rejected (token too old). |
| Lock server leader crash | Raft elects new leader; state is safely replicated. In‑flight client requests may time out; clients retry (idempotent operations are safe). |
| Lock server minority partition | Minority cannot reach quorum → no new lock operations; existing locks continue until TTL expiry. This is acceptable (availability sacrifice). |
| Concurrent acquires | Serialized by Raft; only one succeeds. Others receive “locked” response. |
| Lost or duplicated messages | All operations are idempotent or safe to retry. For Acquire, the client can attach a unique request ID; the lock service deduplicates based on (lock_name, client_id, request_id). |
| Clock skew (client vs server) | Irrelevant: TTL is server‑driven.Client only uses returned lease_expires. |
| Slow client / GC pause | If renewal is missed, lease expires → lock lost. Clients should renew aggressively enough. |
| Resource failure | Not directly handled by lock service; but because operations require a valid token, a resource restart can reload current_token from persistent storage (if it persists) or treat all tokens as invalid until refreshed from lock service. |
| Token replay after release | Token is no longer associated with a holder; once a new lock is granted, the new token is higher, so old token is rejected. The resource may also check with lock service that the token is still valid. |
8. Additional Considerations
- Blocking waits: Could be implemented via watches/events in the Raft log (like ZooKeeper) but omitted for simplicity.
- Fairness: Not guaranteed beyond FIFO at the Raft log level; if fairness required, a queue of waiters can be maintained.
- Scalability: All lock operations go through the Raft leader, limiting throughput. For massive scale, sharding lock names across multiple Raft groups is possible.
- Security: Clients authenticate to the lock service (TLS, mTLS). Fencing tokens are unpredictable and scoped to a lock name.
- Recovery: On restart, lock servers load state from Raft snapshot and log; clients lose state and must re‑acquire locks.
9. Summary
The design uses a Raft‑replicated lock manager that hands out leases with strictly increasing fencing tokens. TTLs automatically free locks after failures. Fencing tokens, combined with the resource’s “highest‑token” check, guarantee that only the most recent holder can access the protected resource, even in the presence of partitions or delayed messages. The system tolerates server crashes, client crashes, and network partitions while preserving safety and eventual liveness.