When Retries Make Things Worse: Idempotency, DLQs, and Replay Jobs in AWS Serverless ETL
Nov 26, 2026 · 6 min read
The tenth message
In my last post I used a batch of ten messages to explain partial failures in SQS and Lambda. Nine records were fine. The tenth was malformed, and it could make Lambda process the other nine again. Once I had SQS buffering the bursts, I was also dealing with duplicate writes after downstream timeouts. That’s a different failure from a bad message. The database might have done what I asked before the worker got an answer. From Spikes to Steady Throughput Using SQS and Lambda.
Take that same batch of ten and give the last message a valid payload. In this failure drill, the database commits the write and the worker times out before it can report success. The row is there. The message can come back. What I want to know when it does is whether the second attempt can write that row again.
The tenth message comes back
I’ll call the event crm:lead-update-731. The producer sends that ID with the event. Every attempt to process that update carries the same ID, even if someone sends another SQS message for it later. A second update to the same lead gets its own event ID. If I used the lead ID as my key, I could throw away that second update by mistake.
The SQS event source mapping processes records at least once, so Lambda can process the same record more than once. messageId is useful when I’m looking for a delivery in the logs or telling Lambda which item failed. The ID for the write comes from the payload. Native SQS redrive gives the replayed message a new messageId, so the queue’s ID can’t connect the replay back to the row that already landed. Lambda with SQS · SQS DLQ redrive.
I put the key where the write happens
For an append-only results table, I’d put a unique constraint on the operation key and let the database handle the conflict as part of the insert. An attempt either inserts the result for crm:lead-update-731 or finds that the key has already been used. Both can finish successfully. A separate read followed by an unconditional insert leaves room for two workers to see the same empty result. If the operation updates a current-state row, I’d also check the event version so replaying an old update can’t overwrite a newer one.
A DynamoDB claim is useful when I want to avoid two workers doing expensive work for the same event. I claim the key with a conditional write. A completed claim lets me return success. An active claim makes me return the item for retry. I size the in-progress expiry around how long the original worker can still run, and I make takeover conditional so an old owner can’t mark the new attempt complete. I use DynamoDB TTL for cleanup and check expiry in the worker, since expired items can remain in the table until DynamoDB deletes them. Powertools for AWS Lambda already provides a DynamoDB-backed implementation with in-progress expiry. DynamoDB TTL · Powertools idempotency.
Think back to the timeout. The destination has committed, but I may still have an in-progress claim. When that claim expires, another attempt can take over. I still need the destination to recognize the operation key. If both writes are in DynamoDB, I can save the result and mark the operation complete in one transaction. For an external API that supports idempotency keys, I pass the same key with the request. If the destination has no way to repeat a write safely after an ambiguous timeout, I check what landed before sending another request. I keep completed keys through the replay window or rely on a destination that can recognize them for longer. DynamoDB transactions.
What happens to the other nine
If the handler has time to catch a downstream timeout, I can use ReportBatchItemFailures to return just the tenth item’s messageId on a standard SQS queue. Lambda acknowledges the other nine. If Lambda itself times out before it can return that response, the whole batch can come back. That’s another reason I want each destination write to be safe to repeat. For FIFO, I stop at the first failure and return that item and the ones I haven’t processed yet so they can keep their order. AWS partial batch responses.
The malformed record from the older example needs a different path. A retry won’t repair its JSON. I save the original message or a recoverable reference to durable quarantine before letting Lambda acknowledge it. If the quarantine write fails, the item stays on the retry list. That save needs to tolerate repeat delivery too.
Here’s how I’d split those paths in a standard-queue handler. The helper functions represent the application’s validation, destination write, and quarantine store. This example uses an event source mapping with ReportBatchItemFailures enabled.
import logging
logger = logging.getLogger(__name__)
def lambda_handler(event, context):
failures = []
for record in event["Records"]:
stage = "validate"
try:
try:
payload = decode_and_validate(record["body"])
except InvalidRecord as error:
stage = "quarantine"
persist_quarantine(record, reason=error.code)
else:
stage = "write"
process_event_once(payload)
except Exception as error:
message_id = record["messageId"]
logger.warning(
"Retry stage=%s error=%s message_id=%s",
stage, type(error).__name__, message_id,
)
failures.append({"itemIdentifier": message_id})
return {"batchItemFailures": failures}
Before I send anything back from the DLQ
With a redrive policy, repeated receives can eventually move an event into a dead-letter queue (DLQ). I alert on visible messages there. When I open the logs, I want the event ID when available, the SQS message ID, the receive count, and the stage that failed. That’s enough to start looking for a bad payload, a worker bug, or a destination outage without putting event bodies in the logs. On a standard queue, expiration still uses the original enqueue time, so I set DLQ retention longer than source-queue retention. SQS DLQs and retention.
Suppose the destination is healthy again. I’d start with a few events and check which event IDs have landed before bringing the rest back. With unmodified messages, native SQS redrive lets me set a rate and send them back to the source or another queue of the same type. Native redrive moves messages as they are. For specific records or payload repair, I’d use a separate replay job. It keeps the operation key for the same work and deletes a DLQ record after the replay queue accepts it. If the send succeeds and the delete fails, I can end up sending that copy again. The destination still checks the key. If I’m issuing a correction to an update that already took effect, I give that correction its own event ID and version. Native SQS redrive.
I keep an independent replay queue on a lower concurrency cap and give it a failure route of its own. The database still has to handle live writes and replay together. If the mappings share one Lambda function, I account for both caps in reserved concurrency. AWS’s starting guidance for the source mapping is a visibility timeout of at least six times the function timeout plus the batching window and a maxReceiveCount of at least five, counting receives from the first delivery. For replay, I tune the rate from what I see at the destination and check the submitted IDs against the rows that actually landed. AWS event source configuration · Lambda scaling with SQS.
One row after replay
I can check the failure that opened this post on a laptop. SQLite plays the destination here. I commit the row first, raise a timeout from the worker, then deliver the same event to it again. That checks what the destination does when it gets the same operation twice.
import sqlite3
from contextlib import closing
from tempfile import TemporaryDirectory
def deliver(database, event_id, *, fail_after_commit=False):
with closing(sqlite3.connect(database)) as db, db:
inserted = db.execute(
"INSERT INTO results (event_id) VALUES (?) "
"ON CONFLICT (event_id) DO NOTHING",
(event_id,),
).rowcount
if fail_after_commit:
raise TimeoutError("Worker timed out after committing")
return inserted
with TemporaryDirectory() as directory:
database = f"{directory}/etl.sqlite"
event_id = "crm:lead-update-731"
with closing(sqlite3.connect(database)) as db, db:
db.execute("CREATE TABLE results (event_id TEXT NOT NULL UNIQUE)")
try:
deliver(database, event_id, fail_after_commit=True)
except TimeoutError as error:
print(f"First delivery: {error}")
inserted = deliver(database, event_id)
with closing(sqlite3.connect(database)) as db:
rows = db.execute("SELECT event_id FROM results").fetchall()
assert inserted == 0 and rows == [(event_id,)]
print(f"Replay inserted {inserted} rows. Destination contains {len(rows)} row.")
First delivery: Worker timed out after committing
Replay inserted 0 rows. Destination contains 1 row.
Before I run replay unattended, I want to see that result against the real destination in staging. I force a failure after the commit, send the event through the replay path, then look up the original event ID. I should be able to account for both attempts and find one result in the database.