Lesson 12 of 12 AWS Lambda

Making Functions Idempotent to Handle Duplicate Events

This lesson explains how to design handlers that process a repeated event safely. An idempotent operation gives the same result however many times it runs, and because AWS messaging services and client retries can deliver the same request twice, event-driven handlers must be idempotent.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain why AWS services and client retries can deliver the same request more than once.
  • Describe how an idempotency key and a stored result prevent a repeated request from being processed twice.
  • Recognise how Powertools for AWS Lambda implements idempotency with an Amazon DynamoDB table.
  • Identify services that deduplicate messages themselves, such as Amazon SQS FIFO queues.

Why duplicates happen

Most AWS messaging and event services guarantee at-least-once delivery rather than exactly-once delivery. To make sure no event is lost, they store each event redundantly and deliver it again whenever they cannot be certain that the first delivery succeeded. SQS standard queues, SNS, EventBridge, asynchronous Lambda invocations and stream event source mappings all behave this way, so a function will occasionally receive the same event twice.

Retries add further duplicates. If a client calls an API, the work succeeds, but the response is lost or arrives after the client's timeout, the client cannot tell whether the request worked, so it sends it again. The AWS SDKs retry automatically in this situation. Similarly, if a Lambda function processing an SQS batch fails part-way through, the whole batch returns to the queue, including the messages it had already processed.

For many operations a duplicate is harmless: setting a user's name to the same value twice changes nothing. For others it is serious: charging a card, sending an email or creating an order twice has real consequences. Handlers for such operations must be made idempotent, meaning that processing the same request several times has the same effect as processing it once.

Implementing idempotency

Idempotency ensures that processing the same request more than once has the same effect as processing it once. It is implemented by the following steps.

  1. Choose an idempotency key

    Use a value that identifies the request, such as an order ID, payment ID or client request ID. A hash of the whole payload works when duplicates are exact copies.

  2. Record the key

    Store the key in DynamoDB with a conditional write (attribute_not_exists) before or with the side effect.

  3. Return the stored result

    When the same key arrives again, return the stored result instead of repeating the work.

  4. Mark requests "in progress"

    A concurrent duplicate then waits or fails rather than running in parallel.

  5. Expire old records

    Remove old keys with a DynamoDB TTL, for example after 24 hours.

Example. Powertools for AWS Lambda implements these steps. If the same payment is delivered again within an hour, the stored result is returned and the card is not charged twice.

from aws_lambda_powertools.utilities.idempotency import (
    DynamoDBPersistenceLayer, IdempotencyConfig, idempotent,
)

persistence = DynamoDBPersistenceLayer(table_name="IdempotencyTable")
config = IdempotencyConfig(event_key_jmespath="body.paymentId", expires_after_seconds=3600)

@idempotent(persistence_store=persistence, config=config)
def handler(event, context):
    return charge_card(event["body"])

Built-in deduplication

Some services offer deduplication of their own, but it covers only part of the problem. SQS FIFO queues and SNS FIFO topics discard a message whose deduplication ID matches one sent within the previous five minutes, which prevents a producer's retried send from creating a second message. Many AWS APIs, such as Amazon EC2 RunInstances, accept a client token for the same purpose.

These features stop duplicate sends, but they do not stop the same message from being processed twice. If a consumer processes a message from a FIFO queue and then fails before deleting it, the message becomes visible again and is processed a second time. Handlers should therefore be idempotent even when the source deduplicates messages.

Worked example

The customer charged twice

A payment function is triggered from an SQS standard queue. A customer complains of being charged twice. Logs show the same message was processed twice, two minutes apart.

CauseExplanation
At-least-once deliverySQS standard queues may deliver a message more than once
Visibility timeout too shortProcessing took 40 s but the visibility timeout was 30 s, so the message reappeared while still being handled
No idempotencyThe function charged the card every time it saw the message

The fixes address each cause: the visibility timeout is raised to six times the function timeout, and the function becomes idempotent by recording each payment ID in DynamoDB with a conditional write (attribute_not_exists(paymentId)) before charging. A second delivery finds the record and returns the stored result without charging again. Powertools' idempotency utility implements this pattern.

Check yourself

A function processes messages from a standard SQS queue and never fails. Why must it still be idempotent?

Show answer

Standard queues deliver each message at least once, so a message can occasionally arrive twice. A message also reappears if processing takes longer than the visibility timeout.

Exam Tips

Remember for the exam

  • Duplicate processing caused by retries or at-least-once delivery is solved by making the handler idempotent.
  • Implement idempotency with a key and a DynamoDB conditional write, or the Powertools idempotency utility.
  • Expire old idempotency records automatically with DynamoDB TTL.