Module postgres_lock

Module postgres_lock 

Source
Expand description

PostgreSQL-based distributed locking implementation

This module implements distributed locking using PostgreSQL advisory locks. Advisory locks are a PostgreSQL feature that provides application-level locks with excellent performance and automatic cleanup on connection termination.

§Features

  • Advisory Locks: Uses PostgreSQL’s built-in advisory lock system
  • Session/Transaction Level: Support for both session and transaction locks
  • Automatic Cleanup: Locks automatically released on connection close
  • No External Dependencies: Uses your existing PostgreSQL database
  • Deadlock Detection: PostgreSQL handles deadlock detection automatically

§Lock Types

PostgreSQL advisory locks come in two flavors:

  1. Session Locks: Held until explicitly released or connection closes
  2. Transaction Locks: Automatically released at transaction end

This implementation uses session locks for consistency with the trait API.

§Example

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

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

    // Acquire lock
    let guard = lock.acquire("checkpoint", Duration::from_secs(30)).await?;

    // Do critical work
    println!("Performing checkpoint...");

    // Lock automatically released on drop
    drop(guard);

    Ok(())
}

§Implementation Notes

PostgreSQL advisory locks use a 64-bit integer key. We hash the resource name to generate this key. While hash collisions are theoretically possible, they are extremely rare with a good hash function (we use SipHash via the standard library’s hasher).

Structs§

PostgresDistributedLock
PostgreSQL-based distributed lock implementation