AWS Lambda Triggers: S3, EventBridge, SQS and SNS Explained
A function alone does nothing. Something must call it. This chapter wires the common triggers: S3 (image upload), EventBridge schedule (link to the EC2 start/stop alarm chapter), SQS and SNS. You also learn cold starts, timeouts, retries, layers and environment variables.
In this chapter
- S3 event → Lambda image-resize pattern
- EventBridge schedule for EC2 start/stop
- SQS and SNS as triggers
- Cold starts, timeouts, retries
- Layers and environment variables
1. A story: photos that resize themselves
Meera's campus app stores student photos in S3. Full-size uploads are 5 MB. The student list needs 200 KB thumbnails. She does not want a server watching a folder. She wants: photo lands in S3 → thumbnail appears.
That is an S3 trigger on ObjectCreated, pointing at a Lambda that reads the object, resizes it, and writes to a thumbs/ prefix.
2. Trigger map
Trace an upload event without putting the whole file in it
Upload one test image to the lab bucket. The event can identify the source bucket, key and kind of operation. Lambda can use that reference to fetch the bytes if the job needs them and its role allows the read. The event notification itself is a record about what happened. The image remains an S3 object.
Test by logging only the synthetic bucket and key. If the expected invocation does not appear, check the bucket’s notification filter, the function’s permission to receive the event and Region. If the function starts but cannot read the object, examine its execution role and the actual key it received.
| Trigger | When it fires | Typical use |
|---|---|---|
| Amazon S3 | Object created/removed in a bucket | Image resize, virus scan, ETL kickoff |
| Amazon EventBridge Scheduler / rules | Cron or rate, or AWS event bus events | Nightly reports, EC2 start/stop |
| Amazon SQS | Messages available in a queue | Smooth bursts, retries with backoff |
| Amazon SNS | Message published to a topic | Fan-out alerts to Lambda + email + SMS |
| API Gateway | HTTP request to a route | Public or private HTTP APIs |
3. Cold starts, timeouts and retries
The first request after idle can be slower. Timeouts cut runaway work. Retries can double-charge or double-write if your code is not safe.
- Cold start: AWS creates a new execution environment, pulls your package, starts the runtime. Then your handler runs. Later calls on the same environment are warm and faster.
- Bigger packages and Java/.NET often cold-start slower than Python/Node. Provisioned concurrency keeps environments warm for a price.
- Timeout: function setting, up to 30 minutes for on-demand Lambda Event Functions. Select a timeout from measurements and leave time for expected dependencies. Check the event source limits and retry behavior before raising it.
- Retries: separate event delivery from function execution. If EventBridge cannot deliver an event to Lambda, EventBridge applies its target retry policy. After Lambda accepts an asynchronous event, Lambda handles function errors and tries the handler up to two more times by default. For an SQS event source mapping, a failed message can return after the visibility timeout. The queue’s redrive policy controls when repeated failures go to its dead-letter queue. Use a stable event or business ID so retries do not write the same record twice.
4. Layers and environment variables
A layer is a zip of libraries you attach to many functions (up to 5). Example: a Pillow layer shared by three image functions. Keep the function zip small.
Environment variables store config (bucket names, log level). Total size max 4 KB. Do not put passwords here — use Secrets Manager or SSM.
5. Lab A: S3 → Lambda (notify only)
Full Pillow resize needs a layer; this lab proves the trigger with a log line. Region ap-south-1.
- Create bucket
yourname-lam-pics, Block Public Access on. - Create Lambda
s3-notify-lab, Python 3.12, basic execution role. - Code:
def lambda_handler(event, context):
for r in event.get("Records", []):
b = r["s3"]["bucket"]["name"]
k = r["s3"]["object"]["key"]
print(f"uploaded s3://{b}/{k}")
return {"ok": True}
- Deploy. Configuration → Permissions → role → Add permissions → Attach policies →
AmazonS3ReadOnlyAccess(lab only). Why: later labs that download need s3:GetObject. - Lambda → Add trigger → S3 → bucket
yourname-lam-pics→ Event type All object create events → Suffix.jpg→ Add. Confirm the recursive warning (do not write back to the same prefix you listen on). - Upload:
aws s3 cp cat.jpg s3://yourname-lam-pics/raw/cat.jpg. - CloudWatch logs for
s3-notify-labshould showuploaded s3://yourname-lam-pics/raw/cat.jpgwithin a minute.
6. Lab B: EventBridge schedule → Lambda (EC2 echo)
In the CloudWatch EC2 alarm chapter you stopped idle instances with alarms. Schedules are cleaner for fixed office hours. This lab only prints; add StartInstances/StopInstances when ready.
- Create Lambda
ec2-schedule-echothat printseventand returns ok. - EventBridge → Schedules → Create schedule. Name
office-open-echo. Recurring — Cron:0 9 * * ? *. Time zone Asia/Calcutta. Why: office 9 AM India. - Target: AWS Lambda Invoke → pick
ec2-schedule-echo→ Create. - For a quick test use rate(5 minutes), watch logs, then switch back or delete.
7. SQS and SNS in one minute
Follow one failed queue message back to visibility
Suppose a worker receives message photo-41. SQS hides it for the configured visibility time while the Lambda handler attempts the job. If the batch fails and the message is not deleted, it can be seen and processed again. When partial-batch reporting is configured, the function can report which specific items failed and avoid retrying successful ones solely because a sibling failed.
Give each test event a business ID and record it before doing irreversible work. If the same ID appears again, the handler can recognize a completed job and avoid making a duplicate. When using bucket events, design output keys or a separate output bucket so processing does not repeatedly trigger itself.
- SQS trigger: Lambda polls the queue for you (event source mapping). Good when producers are bursty and you want retry + DLQ.
- SNS trigger: publish once, many subscribers (Lambda, email, HTTPS). Good for alarms and fan-out.
- Permission: the trigger adds a resource-based policy on the function so that service may invoke it.
Cleanup
- Delete schedules, remove S3 trigger, delete functions, empty and delete the bucket.
- Detach extra IAM policies; delete unused roles.
Common errors and fixes
These are synthetic practice situations. Diagnose the signal before changing a resource; no infrastructure changes are needed to read this guide.
An S3 filename containing a space cannot be found by the handler.
The object key in an S3 notification is URL-encoded: a space can appear as a plus sign. Decode it using the documented form-URL decoding rules before using it as an S3 key. Do not blindly replace every plus in an already-decoded filename.
One failed SQS record causes successful work to run again.
By default, a failed batch makes all its messages visible again after the visibility timeout. Partial-batch failure reporting needs both supported event-source configuration and correct handler response logic. Idempotency is still required; enabling a feature does not make side effects exactly-once.
A test event succeeds, but the real trigger fails.
A hand-written JSON event may not have the same envelope as S3, SNS or SQS. Inspect a safe synthetic example of the real service shape and process each record correctly. Keep event parsing separate from the business operation so that missing fields are diagnosed clearly.
Practical FAQ: decisions during real work
Does the same retry count apply to every trigger?
No. Lambda asynchronous function-error retries differ from SQS polling and from the invoking service’s own delivery policy. Identify the invocation path first, then check its retry and failure-destination behavior. Do not apply a universal two-retry rule to every queue or service.
Can an S3 notification list the order of every upload across the bucket?
No. Arrival order is not guaranteed. S3’s sequencer can help compare relevant events for the same object key, not order unrelated keys across a whole bucket. Design an index updater so an older event cannot blindly overwrite newer state.
Does a successful return from an SQS handler keep the messages for later?
Normally no: after a batch is successfully processed, Lambda deletes its messages from the queue. Do not return success if work was silently skipped or exceptions were swallowed. Report failures deliberately so the queue’s retry path can do its job.
8. Interview questions
Q. Name four Lambda triggers.
S3, EventBridge, SQS, SNS (also API Gateway, DynamoDB Streams, ALB…).
Q. What is a cold start?
First invoke on a new environment: download package, start runtime, then handler. Slower than warm invokes.
Q. Why is idempotency important?
Async retries can deliver the same event more than once. Safe handlers do not create duplicate rows or charges.
Q. S3 trigger recursive risk?
If Lambda writes back to the same prefix it listens on, it can loop forever. Write to another prefix or bucket.
Q. Layer vs packing deps in the function zip?
Layer = shared libraries across functions, smaller function zips. Function zip = simple, but duplicated.
Try at home
- Add a second EventBridge schedule that runs at 21:00 Asia/Calcutta and logs "office closed".
- Create an SNS topic, subscribe the Lambda, publish a message, confirm the log.
In short
- Triggers start Lambda; S3, EventBridge, SQS, SNS are the daily ones.
- Cold start = new environment; design for warm and cold.
- Timeouts and retries need idempotent code.
- Layers share libs; env vars hold non-secret config.
Practise this chapter
Check your understanding
Choose an answer, then compare your reasoning with the explanation.
Practice Tasks
Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.
About this scenarioDublin Fitness Club is a fitness business in Dublin. Siobhan Murphy looks after its IT and cloud work. They count money in EUR and run their AWS resources in the eu-west-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.
0 / 12
Easy List functions
See which functions exist in this Region.
List the Lambda functions in eu-west-1.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Invoke a function
Invoke runs the function now and saves its answer in a file.
Invoke dublinfit-orders-fn and save the response to out.json.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Trust policy for a Lambda role
The trust policy says WHO may take the role.
Write a trust policy that lets lambda.amazonaws.com assume the role.
- Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
- In each statement write Effect, Action and Resource.
- Give only what the task needs (least privilege).
- Use double quotes and commas correctly. Click Check answer.
Medium Change timeout and memory
More memory also gives more CPU; timeout stops runaway runs.
Set dublinfit-orders-fn to timeout 30 seconds and memory 512 MB.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Let a function write logs
Without these actions, Lambda logs never appear in CloudWatch.
Allow logs:CreateLogGroup, logs:CreateLogStream, logs:PutLogEvents on arn:aws:logs:*:*:* only.
- Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
- In each statement write Effect, Action and Resource.
- Give only what the task needs (least privilege).
- Use double quotes and commas correctly. Click Check answer.
Medium Producer may only send
The web app should add jobs but never read or delete them.
Allow sqs:SendMessage on arn:aws:sqs:eu-west-1:132788974236:dublinfit-orders only.
- Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
- In each statement write Effect, Action and Resource.
- Give only what the task needs (least privilege).
- Use double quotes and commas correctly. Click Check answer.
Hard Connect an SQS queue to Lambda
An event source mapping makes Lambda poll the queue and process messages in batches.
Create an event source mapping from queue arn:aws:sqs:eu-west-1:132788974236:dublinfit-orders to dublinfit-orders-fn with batch size 10.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Create a Lambda function
Lambda needs the code zip, a runtime, a handler name and an execution role.
Create function dublinfit-orders-fn: runtime python3.12, handler app.handler, role arn:aws:iam::132788974236:role/lambda-basic, code in function.zip.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Set environment variables
Keep settings like table names out of the code.
Set the environment variable TABLE=dublinfit-orders on dublinfit-orders-fn.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Invoke with a JSON payload
In CLI v2, raw JSON needs --cli-binary-format raw-in-base64-out.
Invoke dublinfit-orders-fn with payload {"orderId":"o-101"} (raw JSON) and save the reply in out.json.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Lambda GB-seconds
Lambda bills memory × time.
1,000,000 invocations, 512 MB memory, 200 ms each. How many GB-seconds?
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Hard Let S3 call your function
A resource-based permission is needed before S3 can invoke the function.
Add permission statement s3invoke to dublinfit-orders-fn so s3.amazonaws.com can call lambda:InvokeFunction from bucket arn:aws:s3:::dublinfit-uploads.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Revision, comparison and interview cards
Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.










More cards: Ravi Sir's Cards.