fix(lock): replace invalid SET NX GET with SET NX + GET#646
Merged
Conversation
Reviewer's guide (collapsed on small PRs)Reviewer's GuideReworks Redis distributed lock acquisition to avoid an invalid SET NX GET usage by separating the SET and GET operations, changing the lock acquisition check semantics accordingly. Sequence diagram for updated RedisLockService.tryAcquire lock acquisitionsequenceDiagram
participant Caller
participant RedisLockService
participant Redis
Caller->>RedisLockService: tryAcquire(key, ttl)
activate RedisLockService
RedisLockService->>Redis: SET key instanceId NX EX ttl
Redis-->>RedisLockService: [status reply]
RedisLockService->>Redis: GET key
Redis-->>RedisLockService: value
RedisLockService-->>Caller: value == instanceId
deactivate RedisLockService
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
Hey - I've found 1 issue, and left some high level feedback:
- You can avoid the extra round-trip GET by checking the return value of
lockCommands.set(...)(e.g., whether it returned"OK"or null) to determine lock acquisition instead of issuing a separateget. - The new logic treats
tryAcquireas successful if the current value already equalsinstanceId, even whenNXprevented a new set; if the intent is to report only fresh acquisitions, consider basing the return value solely on theSEToutcome.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- You can avoid the extra round-trip GET by checking the return value of `lockCommands.set(...)` (e.g., whether it returned `"OK"` or null) to determine lock acquisition instead of issuing a separate `get`.
- The new logic treats `tryAcquire` as successful if the current value already equals `instanceId`, even when `NX` prevented a new set; if the intent is to report only fresh acquisitions, consider basing the return value solely on the `SET` outcome.
## Individual Comments
### Comment 1
<location path="src/main/java/io/github/guacsec/trustifyda/integration/lock/RedisLockService.java" line_range="52-53" />
<code_context>
public boolean tryAcquire(String key, Duration ttl) {
- String previous = lockCommands.setGet(key, instanceId, new SetArgs().nx().ex(ttl));
- return previous == null;
+ lockCommands.set(key, instanceId, new SetArgs().nx().ex(ttl));
+ return instanceId.equals(lockCommands.get(key));
}
</code_context>
<issue_to_address>
**issue (bug_risk):** Re-acquiring an existing lock held by the same instance will now incorrectly return true without refreshing the TTL.
With this change, if this instance already holds the lock, `SET NX` becomes a no-op but `GET` still returns `instanceId`, so `tryAcquire` now returns `true` without refreshing the TTL. Previously, `setGet(...nx...)` would have returned the existing value and caused `tryAcquire` to return `false`. This means callers can think they’ve re-acquired/extended the lock when the TTL is unchanged, allowing the lock to expire earlier than expected and be acquired by another instance. If you want the previous behavior, either treat “already held by this instance” as a failure or explicitly refresh the TTL in that case.
</issue_to_address>Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #646 +/- ##
=========================================
Coverage 57.19% 57.19%
Complexity 878 878
=========================================
Files 92 92
Lines 5021 5021
Branches 691 690 -1
=========================================
Hits 2872 2872
Misses 1841 1841
Partials 308 308
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
…lock pattern The previous implementation had two issues: - tryAcquire used SET NX EX GET which Redis rejects (GET + NX is invalid) - release used non-atomic GET + DEL which can delete another instance's lock if the original lock expires between the two calls Rewrite using RedisAPI for proper protocol-level access: - Acquire via SET NX EX and check for OK response in a single atomic call - Release via EVAL Lua script for atomic owner-check-and-delete Fixes guacsec#645 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
ruromero
force-pushed
the
fix/redis-lock-setget-nx
branch
from
July 20, 2026 14:02
2481e4f to
0217d79
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
RedisLockServicefollowing the single-instance Redlock patternRedisDataSourcetoRedisAPIfor protocol-level access with proper return valuesProblems fixed
tryAcquire: UsedsetGet(SET NX EX GET) which Redis rejects —GETcannot be combined withNXrelease: Used non-atomicGET+DEL— if the lock expires between the two calls, another instance's lock gets deletedChanges
SET key value NX EX ttlviaRedisAPI.set(), checking theOKresponse atomicallyEVALfor atomic owner-check-and-delete, preventing race conditions on lock expiryReferences
Test plan
HardenedImageProviderTest)HardenedImageProviderrefresh completes without Redis errorsFixes #645
🤖 Generated with Claude Code