Spring › Redis

Aligning Redisson, SETNX, and DB locks with transactions

Comparing Redisson RLock, Lettuce SETNX spin locks, and PostgreSQL advisory locks, and reproducing overselling caused by unlocking inside @Transactional.

Aligning Redisson, SETNX, and DB locks with transactions

Stock still oversold even with a distributed lock in place. The bug wasn’t in the lock library—it happened because I released the lock before the database transaction committed. I reproduced this race across three lock implementations under the same load and measured both oversold orders and throughput.

Tested with Spring Boot 3.5.5, Kotlin 2.2.10, Java 21, Redisson 3.51.0, Spring Data Redis 3.5.3 (Lettuce 6.6.0), Redis 8.2.1, and PostgreSQL 17.6 on a personal workstation (12 cores, 32GB RAM, Windows + Docker Desktop/WSL2) with a HikariCP pool size of 10.

The problem

I built a first-come, first-served order flow for 100 club event T-shirts. The stock deduction followed a standard sequence: read stock → if greater than 0, decrement by 1 → insert order. To serialize concurrent requests, I acquired a Redisson lock inside a @Transactional method and released it in a finally block. Under load testing, though, total orders still exceeded 100.

I ran each lock implementation three times with 100 items in stock, 200 incoming requests, and 100 concurrent threads. Overselling equals orders - 100.

ApproachOrders (3 runs)Oversold
No lock200 / 200 / 200100 / 100 / 100
Redisson, unlocked inside transaction102 / 112 / 1182 / 12 / 18
SETNX spin lock, unlocked inside transaction146 / 125 / 13246 / 25 / 32
pg_advisory_lock, unlocked inside transaction191 / 200 / 20091 / 100 / 100
Redisson, unlocked outside transaction100 × 30
SETNX spin lock, unlocked outside transaction100 × 30
pg_advisory_xact_lock100 × 30

Regardless of which lock I used, releasing inside the transaction always caused overselling. Moving the unlock outside the transaction produced exactly 100 orders across every run. If the update only touched a single Redis key, atomic commands would solve it without a lock—like the pattern in my post on Redis INCR and Lua scripts. Here I needed to update both the product stock and the orders table in PostgreSQL, so I reached for a lock.

Root cause

Spring’s @Transactional wraps the method call in a proxy and commits the transaction after the method returns. When you unlock inside the method’s finally block, the lock passes to the next thread while your transaction is still uncommitted.

sequenceDiagram
    participant A as Request A
    participant L as Distributed Lock
    participant D as PostgreSQL
    participant B as Request B
    A->>L: Acquire lock
    A->>D: Read stock 10, UPDATE to 9
    A->>L: Unlock in finally
    B->>L: Acquire lock
    B->>D: Read stock (still 10, uncommitted)
    A->>D: Proxy runs COMMIT
    B->>D: UPDATE to 9 and COMMIT

Under PostgreSQL’s default READ COMMITTED isolation level, Request B reads the pre-commit value from Request A. The same Lost Update anomaly I reproduced in my post on transaction isolation levels and MVCC still happens even with a lock guarding the code.

The gap in oversold counts comes down to how fast each lock hands off to the next waiter. Redisson notifies waiting clients over Redis Pub/Sub, and the woken thread runs a Lua script to claim the lock; by the time that round trip finishes, Request A’s commit has usually completed. The spin lock retries every 5ms, so it caught the uncommitted window much more often. pg_advisory_lock hands off directly inside PostgreSQL, so the next waiter almost always read stale stock before commit. In short, the faster the lock handoff, the worse this boundary bug looks.

The fix

Acquire the lock outside the transaction, and release it only after the @Transactional method returns and commits. If you use a PostgreSQL advisory lock, switch to pg_advisory_xact_lock so PostgreSQL releases it automatically when the transaction ends.

1
2
3
4
5
6
7
// build.gradle.kts
dependencies {
    implementation("org.springframework.boot:spring-boot-starter-data-redis")
    implementation("org.springframework.boot:spring-boot-starter-jdbc")
    implementation("org.redisson:redisson:3.51.0")
    runtimeOnly("org.postgresql:postgresql")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// src/main/kotlin/com/example/club/config/RedissonConfig.kt
package com.example.club.config

import org.redisson.Redisson
import org.redisson.api.RedissonClient
import org.redisson.config.Config
import org.springframework.boot.autoconfigure.data.redis.RedisProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
class RedissonConfig {
    @Bean(destroyMethod = "shutdown")
    fun redissonClient(props: RedisProperties): RedissonClient {
        val config = Config()
        config.useSingleServer().address = "redis://${props.host}:${props.port}"
        return Redisson.create(config)
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// src/main/kotlin/com/example/club/stock/StockService.kt
package com.example.club.stock

import org.redisson.api.RedissonClient
import org.springframework.jdbc.core.simple.JdbcClient
import org.springframework.stereotype.Component
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.util.concurrent.TimeUnit

@Service
class StockService(private val jdbc: JdbcClient) {

    @Transactional
    fun decrease(productId: Long): Boolean {
        val stock = jdbc.sql("select stock from product where id = :id")
            .param("id", productId).query(Int::class.java).single()
        if (stock <= 0) return false
        jdbc.sql("update product set stock = :stock where id = :id")
            .param("stock", stock - 1).param("id", productId).update()
        jdbc.sql("insert into orders(product_id) values (:id)").param("id", productId).update()
        return true
    }

    // DB lock: released automatically on commit/rollback, so the boundary always aligns
    @Transactional
    fun decreaseWithAdvisoryLock(productId: Long): Boolean {
        jdbc.sql("select pg_advisory_xact_lock(:id)").param("id", productId).query().singleRow()
        return decrease(productId) // plain method call within the same transaction
    }
}

@Component
class StockFacade(
    private val stockService: StockService,
    private val redisson: RedissonClient,
) {
    fun decrease(productId: Long): Boolean {
        val lock = redisson.getLock("lock:stock:$productId")
        check(lock.tryLock(10, TimeUnit.SECONDS)) { "lock timeout" }
        try {
            return stockService.decrease(productId) // already committed when this returns
        } finally {
            lock.unlock()
        }
    }
}

Don’t put @Transactional on StockFacade. If you do, the outer transaction expands around the try/finally block, and you’re right back to unlocking before commit.

Throughput comparison and selection guide

Next, I benchmarked all three fixed implementations under the same contention profile: 2,000 requests, 50 concurrent threads, all targeting a single product. I ran each case four times, dropped the first run as warmup, and took the median of the remaining three. Because this ran on a workstation with other processes active, treat these numbers as a relative comparison rather than absolute production capacity.

ApproachThroughputp50p99Notes
Redisson RLock256 req/s187ms1,114msPub/Sub wake-up for waiters
SETNX spin lock (5ms retry)268 req/s4.2ms1,631ms~60,000 SET NX attempts
pg_advisory_xact_lock368 req/s28ms1,043msHolds DB connection while waiting
1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "type": "bar",
  "data": {
    "labels": ["Redisson", "SETNX spin", "PG advisory xact"],
    "datasets": [
      { "label": "p50 (ms)", "data": [187.31, 4.15, 28.06], "backgroundColor": "#7aa2f7" },
      { "label": "p99 (ms)", "data": [1114.26, 1631.27, 1043.14], "backgroundColor": "#f7768e" }
    ]
  },
  "options": {
    "plugins": { "title": { "display": true, "text": "Latency including lock wait (2,000 requests, 1 hot key)" } }
  }
}

The spin lock posted the lowest p50 but the worst p99. Threads that just released the lock—or happened to poll at the right millisecond—kept winning repeatedly while unlucky threads starved for seconds. Processing 2,000 requests also triggered roughly 60,000 SET NX calls (30 per request), adding unnecessary load to Redis. Redisson distributed turns more evenly, narrowing the gap between p50 and p99. PostgreSQL’s advisory lock achieved the highest throughput by avoiding Redis round trips, yet waiting threads held HikariCP connections the entire time—threatening unrelated APIs sharing the same pool. Its p50 also swung widely across runs (27–135ms).

ScenarioRecommended choice
Data lives in one database, low contentionpg_advisory_xact_lock or SELECT ... FOR UPDATE
Multiple app instances, potentially long wait timesRedisson RLock (watchdog auto-extends lease)
Fail fast if work is already in progress (no waiting)Single SET NX PX attempt
High contention on a hot key with waiting callersAvoid spin locks

When not to use a distributed lock: for a single-row stock decrement like this, a conditional SQL statement such as update product set stock = stock - 1 where id = ? and stock > 0 checked via its affected row count is simpler and faster. Also keep in mind that a single-node Redis lock can disappear during failover. Whenever broken mutual exclusion would corrupt data, back the lock with database constraints, conditional updates, or an optimistic version column as your final safety net.

Production caveats and checklist

Adding redisson-spring-boot-starter replaces Spring’s RedisConnectionFactory with Redisson’s implementation. During my tests, StringRedisTemplate switched from Lettuce to RedissonConnection and threw UnsupportedOperationException inside RedissonConnection.execute(). If you want to keep Lettuce for existing Redis code and use Redisson strictly for locks, depend only on org.redisson:redisson and register the RedissonClient bean manually as shown above. Separately, avoid session-scoped pg_advisory_lock with connection pools: if an exception skips the unlock, the lock stays held even after the connection returns to the pool.

  • Are the locking method and the @Transactional method separated into distinct Spring beans?
  • Have you verified with a concurrency test that unlock happens strictly after commit?
  • Have you defined a lock wait timeout and clear failure behavior (such as retry guidance or HTTP 429/409)?
  • When using DB locks, have you confirmed waiting threads won’t exhaust the HikariCP pool?
  • Do you have a database constraint or conditional UPDATE as a final safeguard if the lock fails?
This post is licensed under CC BY 4.0 by the author.