CouchbaseLock
Acquire a distributed lock using Couchbase, with optional callback for automatic lock management.
Syntax
// With callback (automatic lock management)
couchbaseLock(cacheName, name, [timeout], [expires], [callback], [throwOnTimeout])
// Without callback (manual lock management)
couchbaseLock(cacheName, name, [timeout], [expires], [throwOnTimeout])Parameters
cacheName
String
Yes
-
Name of the Couchbase cache for locking
name
String
Yes
-
Unique name of the lock
timeout
Integer
No
5
Maximum seconds to wait for lock acquisition
expires
Integer
No
30
Lock expiration in seconds (max 30)
callback
Function
No
-
Function to execute while holding lock
throwOnTimeout
Boolean
No
true
Throw exception if lock not acquired
Returns
With callback: Returns the result of the callback function
Without callback: Returns struct:
Examples
Callback Mode (Recommended)
Manual Mode
With Custom Timeout
Payment Processing
Batch Job Coordination
Rate Limiting
Sequential Processing
Notes
Distributed: Lock works across all servers in the cluster
30 Second Max: Couchbase limits lock duration to 30 seconds
Auto-Expiry: Locks automatically expire after specified duration
CAS-Based: Unlock requires correct CAS value from acquisition
Callback Safer: Callback mode ensures lock is always released
Manual Control: Manual mode provides fine-grained control
Lock Behavior
With Callback
Lock acquired before callback execution
Callback executes with lock held
Lock automatically released after callback (even on exception)
Returns callback result or throws callback exception
Without Callback
Returns lock info immediately
You must manually unlock using
couchbaseUnlock()Always use try/finally to ensure unlock
Lock auto-expires after
expiresseconds
Error Handling
With throwOnTimeout=true (default)
With throwOnTimeout=false
Best Practices
✅ DO
Use callback mode for automatic cleanup
Keep critical sections short
Set appropriate timeouts
Use descriptive lock names with IDs
Always unlock in finally block (manual mode)
❌ DON'T
Don't hold locks during I/O operations
Don't nest locks (deadlock risk)
Don't set expires > 30 seconds
Don't forget to unlock (manual mode)
Don't use locks for simple caching
Related Functions
couchbaseUnlock - Release lock manually
CouchbaseLock Component - Component version
See Also
Last updated
Was this helpful?
