-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamodb_conditional_write.py
More file actions
29 lines (24 loc) · 968 Bytes
/
Copy pathdynamodb_conditional_write.py
File metadata and controls
29 lines (24 loc) · 968 Bytes
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
"""
Conditional write for idempotent-ish processing (e.g., SQS worker with retries).
If the item already exists with the same idempotency key, ConditionalCheckFailedException
is raised — treat as success (duplicate delivery).
"""
import boto3
from botocore.exceptions import ClientError
dynamodb = boto3.resource("dynamodb", region_name="us-east-1")
def record_processed_message(table_name: str, message_id: str, payload: dict) -> bool:
"""
Returns True if this message_id was recorded for the first time.
Returns False if another worker already recorded it (duplicate).
"""
table = dynamodb.Table(table_name)
try:
table.put_item(
Item={"pk": f"MSG#{message_id}", "data": payload},
ConditionExpression="attribute_not_exists(pk)",
)
return True
except ClientError as e:
if e.response["Error"]["Code"] == "ConditionalCheckFailedException":
return False
raise