Stop 11 · Serverless & Event-Driven AppsTopics · 2/10

Lambda Triggers & Event Sources

Part of the AWS Roadmap

In short

A Lambda function does nothing until something calls it. How it's called, by a waiting API, a fire-and-forget event or a queue being polled, changes how errors and retries behave.

Lambda can be invoked synchronously (API Gateway), asynchronously (S3 events, SNS, EventBridge) or by polling event source mappings (SQS, DynamoDB Streams, Kinesis). The invocation type affects retries and error handling.

The jaadu as a busy tailor stitches at a counter while one customer waits, a note drops into a box behind him, and a neat pile of bundled orders sits beside him.

Think of it like this

Three ways to reach the tailor

You can stand at the tailor's counter in Surat and wait while he fixes your button (synchronous). You can drop clothes in his box with a note and leave, and his assistant retries if he's busy (asynchronous). Or the tailor himself walks over to the pile of orders every few minutes and picks up a bundle (polling). Lambda has exactly these three invocation styles.

Watch it happen

Invocation types and their sources

Lambda
Synchronous
Asynchronous
Event source mapping
API Gateway, ALB
S3, SNS, EventBridge
SQS, DynamoDB Streams, Kinesis

1/4Same function code, three very different callers.

The big ideas

What you need to know

Synchronous

Request in, response out. API Gateway waits for your return value and sends it to the user.

Asynchronous

S3, SNS and EventBridge hand the event to Lambda and don't wait. Configure retries, maximum event age and on-failure destinations.

Event source mappings

For SQS, Kinesis and DynamoDB Streams, Lambda polls for you and invokes with a batch of records.

Design for retries

Any trigger can deliver an event more than once. Make handlers idempotent, for example by checking an order ID before charging.

See it in code

Walk through the code

python
1import json2 3def handler(event, context):4    failures = []5    for record in event["Records"]:6        try:7            order = json.loads(record["body"])8            process_order(order)9        except Exception as err:10            print(f"Failed {record['messageId']}: {err}")11            failures.append({"itemIdentifier": record["messageId"]})12 13    # Only these messages go back to the queue14    return {"batchItemFailures": failures}15 16def process_order(order):17    if order["amount"] <= 0:18        raise ValueError("invalid amount")19    print("Processing order", order["orderId"])

1/4An SQS trigger sends a batch, so loop over event['Records'].

A Python handler for an SQS event source mapping with ReportBatchItemFailures turned on in the mapping settings.

Save yourself the pain

Common mistakes

Oops

Raising an exception for one bad message, so the whole SQS batch is retried again and again.

Do this instead

Turn on partial batch responses and return batchItemFailures, and set a dead-letter queue on the source queue.

Oops

Writing output to the same S3 bucket and prefix that triggers the function.

Do this instead

That can loop forever. Write to a different bucket, or filter the trigger by prefix or suffix.

Your mission

Wire up three triggers

~35 min

Quick check

An S3 upload triggers your function and it throws an error. What does Lambda do by default?

Go deeper

  1. 1Trigger a function from an S3 upload and log the object key.
  2. 2Set up an SQS event source mapping and send a batch of messages.
  3. 3Configure a destination or dead-letter queue for failed asynchronous invocations.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge