Distributed Systems··3 min read

Why Distributed Locks in Redis Fail Under Clock Drift (And How Fencing Tokens in PostgreSQL Saved Our Inventory)

Shafikul Islam

Shafikul Islam

Backend & Cloud Infrastructure Engineer · Infrastructure & Cloud Team Lead

Why Distributed Locks in Redis Fail Under Clock Drift (And How Fencing Tokens in PostgreSQL Saved Our Inventory)

When a Redis Lock Expires Before the Worker Finishes

Many backend teams reach for Redis SET resource_name my_random_value NX PX 5000 when two workers should not mutate the same inventory record or invoice at the same time.

In calm traffic, a 5-second TTL lock looks safe. Under real load, a worker process can pause for 6 seconds due to a container CPU throttle, a slow network socket, or an NTP clock step on a node.

Here is the exact failure sequence we hit in production:

  1. Worker A acquires the Redis lock with a 5-second TTL.
  2. Worker A pauses for 5.4 seconds before sending its SQL UPDATE to PostgreSQL.
  3. Redis expires the lock at 5.0 seconds.
  4. Worker B acquires the same Redis lock, reads the state, and commits its write to PostgreSQL.
  5. Worker A wakes up, still believing it holds the lock, and overwrites Worker B's committed row.

1. Why Redlock Alone Does Not Solve Storage-Layer Split Brain

Even if you run a 5-node Redlock quorum, the lock service cannot pause a zombie network packet that is already in flight from Worker A to PostgreSQL. Once the lock TTL expires, the storage engine itself must reject stale writers.


2. Generating Monotonic Fencing Tokens

Instead of trusting a boolean lock check in the application worker, every lock acquisition increments a monotonic 64-bit counter (fencing_token) and passes that integer down to PostgreSQL:

func AcquireFencedLock(ctx context.Context, rdb *redis.Client, key string) (int64, error) {
    // Lua script atomically sets lock and increments monotonic fencing sequence
    script := `
    if redis.call("SET", KEYS[1], ARGV[1], "NX", "PX", ARGV[2]) then
        return redis.call("INCR", KEYS[2])
    end
    return -1
    `
    res, err := rdb.Eval(ctx, script, []string{key, key + ":fence"}, workerID, 5000).Int64()
    if err != nil || res == -1 {
        return 0, ErrLockContention
    }
    return res, nil
}

3. Enforcing the Fencing Token in PostgreSQL

On the PostgreSQL table, we store last_fence_token BIGINT NOT NULL DEFAULT 0. Every state mutation checks that the incoming token is strictly greater than the stored token:

UPDATE inventory_skus
SET reserved_qty = reserved_qty + $1,
    last_fence_token = $2,
    updated_at = NOW()
WHERE sku_id = $3
  AND last_fence_token < $2;

When Worker A wakes up late with fencing_token = 41 after Worker B has already committed with fencing_token = 42, PostgreSQL matches 0 rows and rejects the stale write cleanly. Zero split-brain corruption.

Infrastructure & PostgreSQL Advisory

Scaling Infrastructure or Diagnosing P95 Latency?

I help engineering teams diagnose PostgreSQL indexing bottlenecks, concurrency limits, and K3s/Docker deployments. Book a 20-minute call with me to review your setup.

Related Technical Articles