Sobes.tech
Junior — Middle

Have you used locking mechanisms in Redis for data synchronization?

sobes.tech AI

Answer from AI

Yes, Redis can implement locking mechanisms for data synchronization, for example, using the SET command with the NX (set if not exists) and PX (expiration time) parameters. This allows creating a simple distributed lock:

import redis
import time

r = redis.Redis()

lock_key = "resource_lock"
lock_timeout = 5000  # milliseconds

# Attempt to acquire the lock
if r.set(lock_key, "locked", nx=True, px=lock_timeout):
    try:
        # Critical section
        print("Lock acquired, working...")
        time.sleep(2)  # simulate work
    finally:
        r.delete(lock_key)  # release the lock
else:
    print("Could not acquire lock")

For more complex scenarios, the Redlock algorithm is used, which provides reliable distributed locking.

Have you used locking mechanisms in Redis for data… - sobes.tech