Skip to content

Lesson 3 of 9 · 24m

Timeouts, Retries, and Idempotency

Partial completion, duplicate delivery, retry storms, poison messages, and designing operations that can safely run twice.

The first serious serverless incident sounds like this: "the function timed out, but the payment still went through." That is not a contradiction. The invocation can fail after the real work succeeded but before the response returned. Correct Lambda design assumes duplicate and partial execution from day one.

A timeout is not error handling

A timeout kills the invocation without a graceful shutdown. Choose it from the shape of the work, not the maximum allowed value:

ApiFunction:
  Type: AWS::Serverless::Function
  Properties:
    Timeout: 8

NightlyExportFunction:
  Type: AWS::Serverless::Function
  Properties:
    Timeout: 600

Too short and retries multiply load. Too long and broken invocations burn money while downstream systems stall. For loops over records, watch the deadline:

def handler(event, context):
    for record in event["Records"]:
        if context.get_remaining_time_in_millis() < 1500:
            raise RuntimeError("retry remaining work")
        process(record)

Every operation must tolerate duplication

SQS redelivers when visibility expires, streams retry according to shard semantics, and EventBridge has its own delivery behavior. The same logical operation will eventually arrive twice. Carry a stable operation identifier end to end:

def handler(event, context):
    key = event["detail"]["idempotencyKey"]
    if already_processed(key):
        return {"status": "duplicate"}
    charge_payment(event["detail"]["paymentId"], idempotency_key=key)
    mark_processed(key)

Stripe's idempotency keys are the canonical external example: repeating a request with the same key does not create a second charge.

Protect state transitions, not just messages

The duplicate may be a second click, a redelivered message, or a replayed event. Make the business transition itself conditional:

UPDATE orders
SET status = 'paid'
WHERE id = $1
  AND status = 'pending';

If zero rows update, the transition already happened. That is stronger than merely remembering message IDs.

Poison messages need a dead-letter path

A permanently failing message should not block the pipe forever:

{
  "deadLetterTargetArn": "arn:aws:sqs:us-east-1:123456789012:orders-dlq",
  "maxReceiveCount": 5
}

The DLQ is not a trash can. Alarm on its depth, preserve the original payload, and redrive gradually after fixing the underlying bug.

Field notes

  • Return success only when the message was processed or intentionally discarded; raise deliberately for retryable failure.
  • SDKs already retry many calls. Layering aggressive retries can multiply attempts unexpectedly.
  • Idempotency records need retention aligned with retry and replay windows.
  • Test duplicate delivery in staging. If it only works exactly once, it does not work.

Was this lesson helpful?

Sign in to rate