Redlock Python Client

1.2.0 · active · verified Thu Apr 16

redlock is a Python implementation of the Redlock algorithm for distributed locks with Redis. It provides a simple API to acquire and release locks across multiple Redis instances to ensure reliability in distributed systems. The current version is 1.2.0, with a release cadence that is not very frequent, suggesting a stable but less actively developed library.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize Redlock with a single Redis instance (for demonstration) and acquire/release a distributed lock. In a real-world scenario, you should configure multiple independent Redis master instances to leverage the Redlock algorithm's fault tolerance. The `lock_ttl` is specified in milliseconds.

import redis
from redlock import Redlock
import os

# Configure Redis instances. For production, use multiple instances
# and ensure they are properly configured for high availability.
# Here, we default to localhost for a runnable example.
redis_host = os.environ.get('REDIS_HOST', 'localhost')
redis_port = int(os.environ.get('REDIS_PORT', 6379))

redis_masters = [
    {"host": redis_host, "port": redis_port, "db": 0}
    # For true distributed locking, add more Redis instances:
    # {"host": "192.168.1.30", "port": 6379, "db": 0},
    # {"host": "192.168.1.31", "port": 6379, "db": 0}
]

# Initialize Redlock with Redis instances
dlm = Redlock(redis_masters=redis_masters)

resource_name = "my_critical_resource"
lock_ttl = 5000  # Lock validity time in milliseconds (5 seconds)

print(f"Attempting to acquire lock for resource: {resource_name}")
lock_info = dlm.lock(resource_name, lock_ttl)

if lock_info:
    print(f"Successfully acquired lock: {lock_info}")
    try:
        # --- Critical section begins ---
        print("Performing critical operation...")
        # Simulate work
        import time
        time.sleep(2) # Keep operation less than lock_ttl
        # --- Critical section ends ---
    finally:
        print("Releasing lock...")
        dlm.unlock(lock_info)
        print("Lock released.")
else:
    print(f"Failed to acquire lock for resource: {resource_name}. It might be held by another process.")

view raw JSON →