Skip to main content

Module redis_lock

Module redis_lock 

Source
Expand description

Redis-based distributed locking implementation

This module implements distributed locking using Redis with the following features:

  • Atomic Operations: Uses Redis SET NX EX for atomic lock acquisition
  • Token-based Ownership: UUID tokens prevent accidental release by wrong holder
  • Automatic Expiration: TTL ensures locks don’t persist after crashes
  • Fair Queuing: Optional FIFO queue for lock waiters
  • LUA Scripts: Atomic multi-command operations

§Redis Lock Implementation

The implementation uses the algorithm recommended by Redis documentation:

  1. Acquire: SET resource token NX EX ttl
  2. Release: LUA script to verify token and delete
  3. Extend: LUA script to verify token and update expiration

§Example

use processor::state::distributed_lock::{RedisDistributedLock, DistributedLock};
use std::time::Duration;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let lock = RedisDistributedLock::new("redis://localhost:6379").await?;

    // Try to acquire lock
    if let Some(guard) = lock.try_acquire("resource", Duration::from_secs(30)).await? {
        println!("Lock acquired!");
        // Do work...
        drop(guard);
    } else {
        println!("Lock already held by another instance");
    }

    Ok(())
}

Structs§

RedisDistributedLock
Redis-based distributed lock implementation
RetryConfig
Configuration for lock acquisition retries