Skip to content

Commit a39e101

Browse files
fix(idempotency): Redis persistence layer reclaims live in-progress records as orphans, allowing concurrent double-execution (#8387)
* fix(idempotency): Redis persistence layer reclaims live in-progress records as orphans, allowing concurrent double-execution RedisCachePersistenceLayer._put_in_progress_record() only guarded against a competing invocation when the existing record's in_progress_expiry_timestamp was set AND still in the future. When that field is None -- which is the normal case for idempotent_function, since it never calls config.register_lambda_context(), unlike the idempotent() handler decorator -- the guard was skipped entirely and a genuinely still-running invocation's record fell through to the "orphan record" branch, which unconditionally overwrites the record with no NX guard. A second concurrent invocation with the same idempotency key would then proceed to execute the underlying function too, defeating idempotency (e.g. double-charging a customer). This is exactly what persistence/base.py's own warning at that call site flags ("Couldn't determine the remaining time left. Did you call register_lambda_context on IdempotencyConfig?") -- it warns, but nothing downstream actually failed closed on it. The DynamoDB persistence layer does not have this gap: its conditional expression requires attribute_exists(#in_progress_expiry) before allowing an expired-in-progress reclaim, so a missing attribute correctly blocks the competing writer instead of granting a reclaim. Fix: when status is INPROGRESS and in_progress_expiry_timestamp is None, treat the record as still in progress (fail closed) instead of falling through to the orphan-reclaim path, mirroring the DynamoDB layer's behavior. * test(idempotency): cover concurrent cache execution --------- Co-authored-by: Leandro <lcdama@amazon.pt>
1 parent 78fdd32 commit a39e101

2 files changed

Lines changed: 85 additions & 4 deletions

File tree

‎aws_lambda_powertools/utilities/idempotency/persistence/redis.py‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -425,10 +425,12 @@ def _put_in_progress_record(self, data_record: DataRecord) -> None:
425425
# (meaning the timestamp is greater than the current timestamp in milliseconds), then we have encountered
426426
# a valid in-progress record. This indicates that another process is currently handling the request, and
427427
# to maintain idempotency, we raise an error to prevent concurrent processing of the same request.
428-
if (
429-
idempotency_record.status == STATUS_CONSTANTS["INPROGRESS"]
430-
and idempotency_record.in_progress_expiry_timestamp
431-
and idempotency_record.in_progress_expiry_timestamp > int(now.timestamp() * 1000)
428+
#
429+
# Without an in-progress expiry, we cannot safely distinguish an active invocation from a timed-out one.
430+
# Fail closed until the record TTL expires, consistent with the DynamoDB persistence layer.
431+
if idempotency_record.status == STATUS_CONSTANTS["INPROGRESS"] and (
432+
idempotency_record.in_progress_expiry_timestamp is None
433+
or idempotency_record.in_progress_expiry_timestamp > int(now.timestamp() * 1000)
432434
):
433435
raise IdempotencyItemAlreadyExistsError
434436

‎tests/functional/idempotency/_redis/test_redis_layer.py‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import datetime
44
import json
55
import time as t
6+
from threading import Event, Lock as ThreadLock, Thread
67
from unittest import mock
78

89
import pytest
@@ -26,6 +27,7 @@
2627
STATUS_CONSTANTS,
2728
DataRecord,
2829
)
30+
from aws_lambda_powertools.utilities.idempotency.persistence.cache import CachePersistenceLayer
2931
from aws_lambda_powertools.utilities.idempotency.persistence.redis import (
3032
RedisCachePersistenceLayer,
3133
)
@@ -198,6 +200,16 @@ def valid_record():
198200
)
199201

200202

203+
@pytest.fixture
204+
def in_progress_record_missing_expiry():
205+
return DataRecord(
206+
idempotency_key="test_orphan_key",
207+
status=STATUS_CONSTANTS["INPROGRESS"],
208+
expiry_timestamp=int(datetime.datetime.now().timestamp()) + 60,
209+
in_progress_expiry_timestamp=None,
210+
)
211+
212+
201213
@mock.patch("aws_lambda_powertools.utilities.idempotency.persistence.redis.redis", MockRedis())
202214
def test_redis_connection_standalone():
203215
# when RedisCachePersistenceLayer is init with the following params
@@ -303,6 +315,73 @@ def test_redis_orphan_record_lock(orphan_record, valid_record):
303315
)
304316

305317

318+
@mock.patch("aws_lambda_powertools.utilities.idempotency.persistence.redis.redis", MockRedis())
319+
def test_redis_in_progress_record_missing_expiry_is_not_treated_as_orphan(in_progress_record_missing_expiry):
320+
layer = RedisCachePersistenceLayer(host="host")
321+
layer._put_in_progress_record(in_progress_record_missing_expiry)
322+
323+
contender = DataRecord(
324+
idempotency_key=in_progress_record_missing_expiry.idempotency_key,
325+
status=STATUS_CONSTANTS["INPROGRESS"],
326+
expiry_timestamp=in_progress_record_missing_expiry.expiry_timestamp + 60,
327+
in_progress_expiry_timestamp=None,
328+
)
329+
330+
with pytest.raises(IdempotencyItemAlreadyExistsError):
331+
layer._put_in_progress_record(contender)
332+
333+
stored_record = layer._get_record(in_progress_record_missing_expiry.idempotency_key)
334+
assert stored_record.status == STATUS_CONSTANTS["INPROGRESS"]
335+
assert stored_record.expiry_timestamp == in_progress_record_missing_expiry.expiry_timestamp
336+
337+
338+
@pytest.mark.filterwarnings("ignore:Couldn't determine the remaining time left")
339+
def test_idempotent_function_blocks_concurrent_invocation_without_lambda_context():
340+
layer = CachePersistenceLayer(client=MockRedis(host="localhost"))
341+
first_invocation_started = Event()
342+
release_first_invocation = Event()
343+
execution_lock = ThreadLock()
344+
execution_count = 0
345+
first_result = []
346+
first_errors = []
347+
348+
@idempotent_function(data_keyword_argument="record", persistence_store=layer)
349+
def process(record):
350+
nonlocal execution_count
351+
with execution_lock:
352+
execution_count += 1
353+
current_execution = execution_count
354+
355+
if current_execution == 1:
356+
first_invocation_started.set()
357+
if not release_first_invocation.wait(timeout=5):
358+
raise TimeoutError("Timed out waiting to release the first invocation")
359+
360+
return {"execution": current_execution}
361+
362+
def invoke_first():
363+
try:
364+
first_result.append(process(record={"id": "same"}))
365+
except Exception as exc:
366+
first_errors.append(exc)
367+
368+
first_invocation = Thread(target=invoke_first)
369+
first_invocation.start()
370+
assert first_invocation_started.wait(timeout=2)
371+
372+
try:
373+
with pytest.raises(IdempotencyAlreadyInProgressError):
374+
process(record={"id": "same"})
375+
finally:
376+
release_first_invocation.set()
377+
first_invocation.join(timeout=5)
378+
379+
assert not first_invocation.is_alive()
380+
assert first_errors == []
381+
assert first_result == [{"execution": 1}]
382+
assert execution_count == 1
383+
384+
306385
@mock.patch("aws_lambda_powertools.utilities.idempotency.persistence.redis.redis", MockRedis())
307386
def test_redis_error_in_progress(valid_record):
308387
layer = RedisCachePersistenceLayer(host="host", mode="standalone")

0 commit comments

Comments
 (0)