Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

Project: Build an Image Thumbnail Pipeline with S3, Lambda and DynamoDB (Source Code)

Instagram and WhatsApp compress images after upload. You will do the same: S3 upload triggers Lambda, a thumbnail lands in S3, metadata goes to DynamoDB. Region ap-south-1.

In this chapter

  • S3 event trigger to Lambda
  • Write thumb + DynamoDB row
  • Pillow layer or stub fallback
  • Cleanup buckets and function

1. Everyday example

A course site uploads a 5 MB photo. The gallery needs a 200 px thumb. Doing that on every page view is wasteful — do it once on upload.

ObjectCreated on bucket → Lambda get_object → resize (Pillow layer) or stub copy → put_object under thumbs/ → PutItem metadata.

PipelineUploadS3 originals/EventObjectCreatedLambdaresizeS3thumbs/ + DynamoDB meta
Skip keys that already start with thumbs/.

Download: image-thumbnail-pipeline.zip. Attach a public Pillow layer for real resize, or use the built-in stub path so the lab still verifies.

2. Lab

A. Buckets + table

S3 stores files as objects. The bucket is the named container and the key identifies one object inside it. For an upload called uploads/demo.jpg, uploads/ is a prefix of that key. Name the output under thumbs/ so students can tell which object is the original and which was generated. DynamoDB holds small descriptive fields such as output key and byte size so another program can find the result.

Keep the originals private. The application does not need a public bucket to resize an image. S3 needs permission to invoke the function and the function role needs only its intended object reads, object writes and table update. Tracking those as separate permissions makes a failed invocation easier to diagnose.

  1. Create bucket yourname-imgs (ap-south-1). Block Public Access on.
  2. Optional second bucket for thumbs, or same bucket with prefix thumbs/.
  3. DynamoDB yourname-images, PK imageId String.

B. Lambda

  1. Role: logs + s3:GetObject/PutObject on your buckets + PutItem.
  2. Function Python 3.12, handler.py. Env TABLE_NAME, optional DEST_BUCKET, THUMB_PREFIX=thumbs/.
  3. Optional: Layers → add Pillow community layer for Python 3.12 in ap-south-1.
  4. Timeout 30 s, memory 512 MB.

C. S3 trigger + test

In the same-bucket lab, scope the notification to uploads/. Follow one sample event. S3 creates uploads/demo.jpg and sends Lambda the bucket and key. Lambda reads that object, writes a new object below thumbs/, and records the result in the table. The output key does not begin with uploads/, so that write does not match the upload trigger again.

Use a test image with known width and height and open the output to check dimensions. With the image processor installed, the output should be smaller for a sufficiently large source. With the ZIP’s fallback active, the output can have the same dimensions. Both paths can produce an object and a table row. Only the dimension check proves a resize happened.

  1. S3 → Properties → Event notifications → All object create → Lambda function. Prefix uploads/ optional.
  2. Upload a small JPG to uploads/demo.jpg.
  3. Check thumbs/ object and DynamoDB item (imageId, thumbKey, bytes).

Cleanup

  1. Remove event notification. Delete Lambda. Empty and delete bucket(s). Delete table and role.

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.

Uploads work but Lambda has no invocation.

Separate the ability to upload from the ability of S3 to invoke Lambda. Check whether the notification event and prefix match the uploaded key and whether the function resource policy permits this bucket to invoke it. The execution role used inside the handler is a different permission boundary. Do not make the bucket public to diagnose this.

An object exists, yet the handler gets NoSuchKey.

S3 notification keys use form-style URL encoding. A space can appear as a plus sign, while a literal plus is encoded differently. Decode the event key correctly before GetObject instead of guessing a new filename. Compare a harmless example key with the decoded value, without logging private object contents.

The Pillow layer is attached but imports still fail.

A layer must contain Linux-compatible dependencies built for the function Python version. A zip from a laptop is not automatically compatible with Lambda. Check the import error and the layer package structure, including its top-level python directory. Review the dependency source before using it; attaching an unknown layer is not proof of a working image processor.

Practical FAQ: decisions during real work

What proves that real resizing happened?

A new output key and a metadata row prove wiring, not image dimensions. The documented fallback copies the source when resizing is unavailable. Inspect the output dimensions and format using a synthetic image with known dimensions. Report whether this was a copy-path check or an actual resize check rather than calling both results a thumbnail.

Why can an older upload overwrite newer metadata?

S3 event notifications are not guaranteed to arrive in occurrence order. For repeated writes to the same object key, track the event version or same-key sequencer and reject stale metadata updates as appropriate. A sequencer does not order unrelated object keys. This is an application ordering decision, not something a longer Lambda timeout fixes.

Is saving metadata proof that the whole pipeline finished?

Not by itself. Object output and DynamoDB metadata are separate writes. A failure between them can leave only one result. Make repeat handling safe and define which durable status means processing finished. In diagnosis, check both the destination object and matching metadata instead of assuming either one proves the other exists.

3. Interview

Q. Why not resize in the browser only?

Clients lie; you need a trusted server-side thumb for cards and emails.

Q. Why skip thumbs/ prefix?

Avoid recursive events if thumb lands in the same bucket.

Q. Pillow missing?

Lab stubs a copy so wiring still works; production needs a layer or container image.

Q. Large images?

Raise memory/timeout; consider Step Functions for huge files.

Q. Cleanup?

Notification, Lambda, buckets, table.

Try at home

  1. Write thumbs to a separate bucket with OAC later for CloudFront.
  2. Store contentType in DynamoDB.

In short

  1. S3 event → Lambda → thumb + DynamoDB.
  2. Guard against recursive prefixes.
  3. Layers add native libs like Pillow.
  4. Clean up buckets.

Tell an actual resize from a trigger test

Configure handler.lambda_handler. Use a disposable private bucket and an uploads/ trigger prefix separate from thumbs/, or use two buckets. Upload an image with a unique basename. Download the result and inspect dimensions and Content-Type. A byte-for-byte copy proves event wiring only. If you need real resizing, build a trusted compatible Pillow layer rather than attaching an unknown public layer.

Interview check Why can a same-bucket output create repeated calls?

An output write matches the same notification when the input filter is too broad. Keep input and output prefixes disjoint. The starter derives the thumbnail key from the basename, so two uploads with the same basename can collide.

Reference documentation

Practise this chapter

Interview questions and answers

An upload succeeded, but there is no output. How do you trace the path?

I would first confirm the uploaded key matches the notification’s prefix and S3 can invoke the selected function. If the logs show an invocation, I would inspect that invocation’s object read and write results, then verify the output dimensions and the matching metadata row.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. Which S3 value is the key in s3://lab-images/uploads/demo.jpg?

Answer and explanation

C. uploads/demo.jpg

The bucket is lab-images. The full name inside the bucket includes the uploads prefix and filename.

2. What prevents a generated thumbs/demo.jpg from matching a same-bucket upload notification?

Answer and explanation

B. The trigger requires the uploads/ prefix

S3 compares the object key with the notification filter. thumbs/ does not match uploads/.

3. The lab created an output object and a row. What shows it really resized the image?

Answer and explanation

B. The output dimensions match the smaller target behavior

The fallback can copy the original under a new key. Checking dimensions distinguishes that result from resizing.

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 scenario

Kolhapuri Chappal Co is a footwear business in Kolhapur. Sachin Mane looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-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 ap-south-1.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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 kolhapurichappal-orders-fn and save the response to out.json.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Medium Put an item

DynamoDB JSON shows the type of each value: S for string, N for number.

Put an item into kolhapurichappal-orders with orderId "o-101" (string) and amount 2500 (number).

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium Change timeout and memory

More memory also gives more CPU; timeout stops runaway runs.

Set kolhapurichappal-orders-fn to timeout 30 seconds and memory 512 MB.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

  1. Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
  2. In each statement write Effect, Action and Resource.
  3. Give only what the task needs (least privilege).
  4. Use double quotes and commas correctly. Click Check answer.

Hard Create a Lambda function

Lambda needs the code zip, a runtime, a handler name and an execution role.

Create function kolhapurichappal-orders-fn: runtime python3.12, handler app.handler, role arn:aws:iam::118690042069:role/lambda-basic, code in function.zip.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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=kolhapurichappal-orders on kolhapurichappal-orders-fn.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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 kolhapurichappal-orders-fn with payload {"orderId":"o-101"} (raw JSON) and save the reply in out.json.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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?

  1. Write down the numbers the task gives you.
  2. Work it out step by step on paper.
  3. Type only the final answer in the box.
  4. 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:ap-south-1:118690042069:kolhapurichappal-orders to kolhapurichappal-orders-fn with batch size 10.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. 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 kolhapurichappal-orders-fn so s3.amazonaws.com can call lambda:InvokeFunction from bucket arn:aws:s3:::kolhapurichappal-uploads.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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.

Revision card: Image thumbnail pipeline. A 5 MB course photo should not download full size for every gallery card. You need a small thumb once. Upload to S3 → ObjectCreated invokes Lambda → resize → put thumb under thumbs/ → PutItem metadata in DynamoDB. Bucket yourname-imgs, table PK imageId, Lambda with S3 Get/Put + PutItem, S3 event on uploads/ prefix, optional Pillow layer. Upload uploads/demo.jpg → object thumbs/demo.jpg appears and DynamoDB has imageId, thumbKey, bytes.
Revision card: Image thumbnail pipeline · Download PNG · Open card page
Revision card: Avoid recursive S3 events. If Lambda writes a thumb into the same prefix it listens on, every write fires another invoke forever. Guard: only process keys under uploads/ (or skip any key starting with thumbs/). Write thumbs elsewhere. Event notification prefix uploads/. In code: if key.startswith("thumbs/"): return. Dest prefix THUMB_PREFIX=thumbs/. One upload creates exactly one thumb and one DynamoDB row — CloudWatch shows a single invoke.
Revision card: Avoid recursive S3 events · Download PNG · Open card page
Revision card: Pillow layer vs stub. Python zip uploads cannot easily ship native image libraries. Labs still need a wiring test. A Lambda layer can attach Pillow for real resize. Without it, a stub copies the object so S3+DynamoDB wiring still verifies. Layers › Add a community Pillow layer for Python 3.12 in ap-south-1, or leave stub path on. Memory 512 MB, timeout 30 s. With Pillow, a 2000 px JPG becomes ~200 px wide under thumbs/; without Pillow, thumb bytes ≈ original but flow works.
Revision card: Pillow layer vs stub · Download PNG · Open card page
Comparison: S3 ObjectCreated trigger vs API Gateway HTTP API. S3 ObjectCreated trigger: Upload creates an event automatically. API Gateway HTTP API: Client must call an HTTPS route.
Comparison: S3 ObjectCreated trigger vs API Gateway HTTP API · Download PNG · Open card page
Comparison: Same bucket + thumbs/ prefix vs Separate thumb bucket. Same bucket + thumbs/ prefix: Must skip thumbs/ in code or event prefix. Separate thumb bucket: Natural isolation of originals vs thumbs.
Comparison: Same bucket + thumbs/ prefix vs Separate thumb bucket · Download PNG · Open card page
Interview card: Why skip keys under thumbs/?. Writing the thumb into a watched prefix would invoke Lambda again (recursion). Bills and throttles explode until you delete the notification. Listen on uploads/ only, or if key.startswith("thumbs/"): return before resize.
Interview card: Why skip keys under thumbs/? · Download PNG · Open card page
Interview card: How do you add Pillow to Lambda?. Attach a Lambda layer that contains the Pillow wheel for your runtime and architecture. Zip size limits and native binaries make layers the usual path (or a container image). Function › Layers › Add layer › community Pillow for Python 3.12 x86_64 in ap-south-1.
Interview card: How do you add Pillow to Lambda? · Download PNG · Open card page

More cards: Ravi Sir's Cards.