Redis Fencing Lock Guide

Using Redis Fencing Lock in a Spring Boot Application

When several application instances try to update the same resource, a distributed lock can coordinate access. But a lock by itself cannot stop a paused process from resuming after its lease expires and writing stale data. That is where a fencing token helps.

Redis Fencing Lock is a focused Java and Spring library for Redis-backed locks. It acquires locks, manages leases, checks ownership, and provides a monotonically increasing token. Your application passes that token to the protected resource, which must reject stale writes.

What is a fencing token?

Each successful lock acquisition receives a number greater than the previous token for that resource. If a process pauses, its lease expires, and another process acquires the lock, the new process receives a higher token. The database or other protected system can then reject an older token after it has accepted a newer one.

The lock library does not automatically protect your database. The application must check and record the token atomically where the data is written.

1. Add the dependency

The Spring Boot starter is available from Maven Central. In Gradle, add:

repositories {
    mavenCentral()
}

dependencies {
    implementation("io.github.neephi:redis-fencing-lock-starter:1.0.6")
}

For Maven, add this dependency to your pom.xml:

<dependency>
    <groupId>io.github.neephi</groupId>
    <artifactId>redis-fencing-lock-starter</artifactId>
    <version>1.0.6</version>
</dependency>

The starter integrates through Spring Data Redis. You need a reachable Redis server running Redis 7 or later because the library uses Redis Functions.

2. Configure Redis and the lock

For a local Redis server, a basic application.yml could look like this:

spring:
  data:
    redis:
      host: localhost
      port: 6379

redis-fencing-lock:
  owner-id: ${HOSTNAME:inventory-app}
  default-lease: 30s
  annotation-enabled: true

Choose an owner ID that identifies this application instance in your environment. The annotation aspect is opt-in, so set annotation-enabled to true to use @FencedLock.

3. Inject the token into an annotated method

Here is an inventory reservation example. The service delegates the locked operation to another Spring bean, so the call goes through Spring’s proxy and the aspect can run. The third parameter is the fencing token; its index is 2 because parameter indexes start at zero.

import org.springframework.stereotype.Service;

@Service
public class InventoryReservationService {
    private final LockedInventoryWriter writer;

    public InventoryReservationService(LockedInventoryWriter writer) {
        this.writer = writer;
    }

    public void reserve(String sku, int quantity) {
        // The aspect replaces this placeholder with the acquired token.
        writer.reserveUnderLock(sku, quantity, 0L);
    }
}
import io.github.neephi.spring.FencedLock;
import org.springframework.stereotype.Component;

@Component
public class LockedInventoryWriter {
    private final InventoryRepository inventory;

    public LockedInventoryWriter(InventoryRepository inventory) {
        this.inventory = inventory;
    }

    @FencedLock(value = "inventory:#sku", tokenParameterIndex = 2)
    public void reserveUnderLock(String sku, int quantity, long fencingToken) {
        int updated = inventory.reserveIfTokenIsCurrentOrNewer(
                sku, quantity, fencingToken);

        if (updated != 1) {
            throw new IllegalStateException("Reservation was rejected");
        }
    }
}

The value inventory:#sku creates a lock resource specific to the SKU. The caller’s 0L is only a placeholder—the aspect supplies the token obtained from Redis before invoking the method.

4. Enforce the token in the database

For example, the inventory table could have a last_fencing_token column initialized to 0. The repository should compare and update that column in the same SQL statement as the protected change:

UPDATE inventory
SET available_quantity = available_quantity - :quantity,
    last_fencing_token = :fencingToken
WHERE sku = :sku
  AND available_quantity >= :quantity
  AND last_fencing_token <= :fencingToken;

Using <= allows the current lock holder’s token to be used for more than one update, while a token lower than the highest one already accepted is rejected. Adapt the condition to your database schema and transaction requirements.

If an older process resumes after its lease expires, it cannot overwrite a write already accepted with a newer token. This protection only works if the protected resource performs the token comparison atomically with the write.

Important Spring and lease details

  • The annotated method must be invoked through its Spring bean proxy. Self-invocation from another method in the same bean does not trigger the aspect; delegating to a separate bean, as shown above, avoids that issue.
  • tokenParameterIndex is zero-based and must point to a long or Long parameter. Its default value is -1, which leaves the method arguments unchanged.
  • The default lease is 30 seconds in this example. If work can take longer, configure an appropriate lease or consider the optional watchdog. A watchdog renews active leases, but the protected resource should still validate fencing tokens.
  • For direct lock management or access to token metadata, inject FencedLockManager and use it directly instead of the annotation.

Summary

Redis Fencing Lock provides the lock and the monotonically increasing token. The application decides what work to perform, and the database or other protected system remains responsible for rejecting stale tokens. This separation makes the library useful for workflows such as inventory updates, cache population, and other operations that need coordinated access.

Project: https://github.com/neephi/redis.fencing
Maven Central: redis-fencing-lock-starter