Hacker News new | ask | show | jobs
by samsquire 1465 days ago
How do you ensure that a lock isn't acquired by two requests? Do you use atomic compare and set?

How do you release a lock reliably? How do you solve the problem of releasing accidentally while using a resource?

Can the lock jam locked if the process dies?

I would use Consul for this or I would try avoid needing to lock to begin with.

Even better is to use a language such as bloom Lang.

1 comments

Good questions:

> How do you ensure that a lock isn't acquired by two requests?

Indeed, the compare and set is done atomically. It's guaranteed that the lock can only be acquired by at most one process.

> How do you release a lock reliably? How do you solve the problem of releasing accidentally while using a resource?

A lock is released in one of two conditions:

  1. the /release endpoint is called
  2. the lease on the lock expires
I'm not sure what you mean by "releasing accidentally" - if nobody calls /release then the lock won't be released.

> Can the lock jam locked if the process dies?

Locks come with a lease which expires after a set amount of time. If lockable doesn't receive a heartbeat to renew the lease, the lock is released automatically.

> I would use Consul for this or I would try avoid needing to lock to begin with.

For sure Consul is an alternative, so are ZooKeeper and things like ETCD - lockable is intended to be a no-setup alternative to something like that.

I'm thinking of a case where a process thinks it has a lock and tries to do things even though it doesn't have the lock.

This happened on a project I was on, two processes would join a RabbitMQ on a service that was not safe to load balance.

I suspect it could happen if the program using your lock service is not implemented properly and the lease expires but the program doesn't realise.

Ultimately, you have to trust your clients to do the right thing.

The lockable server guarantees that e.g. if multiple /acquire requests come in for the same lock in a short time span, only one request will be successful. You are correct in that, without care, there can be pathological cases where a client may not realize their lease has expired.

etcd and zookeeper lock are based on a session.

You open a session and the session open many locks.

if you can’t talk to server the session expire and all lock are released by the server but also the client library notify that the sessions expired.

Also etcd and consul and zookeeper use The Raft consensus algorithm. it’s literally impossible to make a lock server that is safe without using a consensus algorithm for replication.