Retrieving information from back end or remote systems might be slow and consume a lot of resources. You can use advisory locks on records in order to control access to these resources. Instead of letting any client access Couchbase Server and potentially overwhelm the server with high concurrent client requests, you could create an advisory lock to allow only one client at a time access the information.
You can create a lock in Couchbase by setting an expiration on
specific item and by using the add()
and delete() methods to access that
named item. The add() and
delete() methods are atomic, so you can
be assured that only one client will become the advisory lock
owner.
The first client that tries to add a named lock item with an
expiration timeout will succeed. Other clients will see error
responses to an add() command on that
named lock item; they will know that some other client owns the
named lock item. When the current lock owner is finished owning
the lock, it can send an explicit
delete() command on the named lock item
to free the lock.
If a client that owns a lock crashes, the lock will
automatically become available to the next client that requests
for lock via add() after the expiration
timeout.
As a convenience, several Couchbase SDKs provide
get-and-lock as a single operation and
single server request. This will accomplish the functional
equivalent of adding a lock and deleting it. The following is an
example from the Python SDK:
import uuid key, value = str(uuid.uuid4()), str(uuid.uuid4()) client.set(key, 0, 0, value) client.getl((key)[2], value) client.set(key, 0, 0, value)
After we set the key and values to unique strings, we lock the
key. The subsequent set() request will
fail and return an error.