Tech challenge · AWS

The same S3 file is processed twice

MediumAWS

An S3 event notification triggers a Lambda function that loads each new file into a database. Occasionally a file is loaded twice. Nobody uploaded it twice. Why can this happen, and how do you make the pipeline safe?

Think it through or sketch an answer first, then open the hint or the solution.

Show a hint

Event delivery is at least once. Lambda can also retry after a failure part-way through.

Show the solution

S3 event notifications are delivered at least once, and asynchronous Lambda invocations are retried on error, so duplicates are expected rather than a bug. Make processing idempotent: record each object key and version (or ETag) in a DynamoDB table with a conditional write, and skip the file if the record already exists, or load with an upsert keyed on business ids.

Example (Python)

import boto3
from botocore.exceptions import ClientError

table = boto3.resource('dynamodb').Table('processed_files')

def already_done(key, etag):
    try:
        table.put_item(Item={'pk': f'{key}#{etag}'},
                       ConditionExpression='attribute_not_exists(pk)')
        return False
    except ClientError as e:
        if e.response['Error']['Code'] == 'ConditionalCheckFailedException':
            return True
        raise

Common mistakes

  • Assuming exactly-once delivery from S3 or Lambda.
  • Marking the file as processed before loading it, so a crash in between loses the file.

Learn more

More AWS challenges

Today's challenge and the full archive