Back to the blog

AWS Lambda and idempotency: the same event can arrive more than once

awsserverlessarchitecturego

Why a serverless function needs to be designed assuming repetition, partial failure and retries.

The dangerous assumption

It is tempting to imagine a Lambda as a function that receives an event exactly once and finishes. In asynchronous integrations, delivery can be repeated. An execution can also complete an external change and fail before recording that it finished.

Idempotency in practice

If the event creates a charge, sends a message or updates a user, processing it twice can cause a real effect. One solution is to define a stable idempotency key, persist the result of the first processing and reject or reuse repetitions.

The key needs to represent the business operation, not just a technical execution. A requestId created again on every attempt does not solve it. It is also necessary to think about concurrency: two instances can look up the key at the same time before either one writes it.

A concrete case appears when a Lambda works as a worker for an SQS queue: the event source mapping delivers messages in batches, and if the function throws an exception or does not respond in time, the message becomes visible in the queue again after the visibility timeout and is delivered once more, possibly to another invocation. The same MessageId can reach the function more than once even without any failure from whoever published the message — and that is why it should not be the idempotency key: it is a transport detail, not the business operation the message carries. With ReportBatchItemFailures enabled, you can mark as failed only the messages that actually failed inside the batch, without reprocessing the ones that had already been completed in the same invocation.

A simplified handler for this worker could look like this:

func handler(ctx context.Context, sqsEvent events.SQSEvent) (events.SQSEventResponse, error) {
    var failures []events.SQSBatchItemFailure

    for _, record := range sqsEvent.Records {
        var payload ChargePayload
        if err := json.Unmarshal([]byte(record.Body), &payload); err != nil {
            failures = append(failures, events.SQSBatchItemFailure{ItemIdentifier: record.MessageId})
            continue
        }

        if alreadyProcessed(ctx, payload.ChargeID) {
            continue // idempotent: already done, skip without failing
        }

        if err := processCharge(ctx, payload); err != nil {
            failures = append(failures, events.SQSBatchItemFailure{ItemIdentifier: record.MessageId})
            continue
        }

        markProcessed(ctx, payload.ChargeID)
    }

    return events.SQSEventResponse{BatchItemFailures: failures}, nil
}

record.MessageId is only used as the identifier for SQS to know which message in the batch failed and should be redelivered — whether the work was already done is decided by payload.ChargeID, the business key persisted through alreadyProcessed/markProcessed.

Partial failure

The most important case is not only the duplicated event, but the execution that does half the work. Separating steps, recording states and carefully choosing the order of the operations makes recovery more predictable. When possible, I prefer external operations that also accept an idempotency key.

Conclusion for now

Serverless changes the operational side, but it does not remove the guarantees the domain needs. In event-driven flows, assuming repetition from the initial design is usually cheaper than fixing duplicates in production.