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

AWS Cloud

What Is AWS Lambda? Serverless Explained with Examples

You have been running code on EC2 for weeks. The server stays on even when nobody calls your API. You still pay for CPU, disk and a public IP. This chapter shows a different way: upload a small function, and AWS runs it only when something happens. That is AWS Lambda.

In this chapter

  • Why keep a server on all day is often waste
  • What serverless, a function, a trigger and an event mean
  • Lambda vs EC2 vs containers — when to pick which
  • Pricing, free tier and limits (30-minute on-demand timeout, memory, package)
  • A tiny lab: run Hello from the Lambda console

1. A story: the bakery light that never sleeps

Ravi runs a small bakery site. Orders come mostly between 7 AM and 10 PM. At 3 AM almost nobody orders. Still, one EC2 instance runs all night. He pays for idle hours.

What he really needs is: when an order arrives, run a bit of code; when nothing arrives, pay almost nothing. That idea is serverless. AWS Lambda is the main serverless compute service on AWS.

2. What is serverless and what is Lambda?

Ask what event starts your code and what makes it finish

Suppose the bakery asks for a function to calculate a delivery price. A caller sends the details as an event. Lambda starts or reuses an execution environment, runs the handler and supplies its result or error to the caller when the invocation is synchronous. The request and the short piece of work define the function’s boundary. Lambda handles the underlying execution infrastructure.

Write the input and expected output for a new delivery with a synthetic address. A listener program on EC2 can remain running while it waits for another request. A Lambda function runs when invoked and should save important state in a durable service. An execution environment can be reused, but a future invocation is not promised the same environment.

Buying, patching and watching servers is work that does not make your app better. For short tasks that start from an event, you want AWS to own the servers.

Serverless does not mean "no servers". It means you do not manage them. You give AWS your code; AWS finds a machine, runs the code, then free that machine.

AWS Lambda is a service that runs your function when an event arrives. You pay for the number of requests and for how long the code runs (GB-seconds). No charge for idle time.

WordMeaningKitchen example
FunctionYour code plus settings (runtime, memory, timeout)The recipe card
TriggerThe service that starts the functionThe doorbell
EventThe JSON data the trigger sendsWho rang and what they want
Execution roleIAM role Lambda assumes to call AWS APIsKitchen keys on a hook
InvocationOne run of the functionOne order cooked
One Lambda requestEvent arrivesS3 / API / schedule / queueLambda finds awarm or new microVMRuns your handlerwith the event JSONWrites logs toCloudWatch LogsReturns a resultor retries on failure
You never SSH in. AWS owns the machine.

3. Lambda vs EC2 vs containers

Interviews and real designs ask this first. Pick wrong and you either waste money or hit Lambda limits.

NeedPreferWhy
HTTP API with short requests, low/variable trafficLambda + API GatewayNo idle cost; scales to zero
Long jobs, custom kernel, GPU, always-on websocketEC2Full control of the OS and process
Same app in many places, needs packing, runs minutes+ECS / EKS / App RunnerContainers travel; longer runtimes
Cron that starts/stops EC2 or cleans S3Lambda + EventBridgeSeconds of work; no server to keep
Image resize on every S3 uploadLambdaEvent-driven; pay per image

Ravindra Bagale's Tip

Lambda is a great glue and a great home for small APIs. It is a bad home for a 2-hour video encode or a sticky in-memory game server.

4. Pricing, free tier and hard limits

Estimate the work before choosing a deployment shape

For a small function, write down how many times it runs, its configured memory and how long an average invocation takes. Multiply memory in GB by duration in seconds and by the invocation count to estimate the compute usage for that example. The product does not include every price. Requests, data transfer and related services can have their own charges.

Now compare a burst of brief delivery requests with a process that needs to remain connected all day. This choice is about the work’s runtime, traffic shape and needs, not the name of the service. Confirm current pricing and platform limits for the chosen invocation path.

Limits decide if your idea fits. Pricing decides if it stays cheap as you grow.

  • Always-free tier (per month, every account): 1 million requests and 400,000 GB-seconds of compute.
  • You pay for requests beyond the free tier and for duration × memory (GB-seconds). More memory also gives more CPU.
  • Timeout: up to 1,800 seconds (30 minutes) for on-demand Lambda Event Functions. Eligible asynchronous and event source mapping invocations on Lambda Managed Instances can use up to 5,400 seconds (90 minutes), excluding Amazon MQ and Amazon DocumentDB event sources. Check the invocation path as well because an upstream integration can have a shorter limit. Lambda quotas
  • Memory: 128 MB to 10,240 MB (1 MB steps). At about 1,769 MB you get roughly one full vCPU.
  • Deployment package: 50 MB zipped via console/API upload; 250 MB unzipped including layers. Larger zips go through S3. Container images up to 10 GB.
  • Sync payload ~6 MB request/response; async ~1 MB. Environment variables total 4 KB. Up to 5 layers.

Example: a 512 MB function that runs 200 ms, one million times. Duration = 0.2 × 0.5 × 1,000,000 = 100,000 GB-seconds — well inside the free 400,000. Many student projects stay free.

5. Worked examples across stacks

  1. Python Flask on EC2 → move the /resize route to a Lambda behind API Gateway; keep the admin UI on EC2.
  2. Node.js Express image API → one Lambda per route or one Lambda with a router (AWS Lambda Web Adapter / Mangum-style).
  3. Java Spring Boot batch job nightly → EventBridge cron triggers a Lambda that starts an ECS task for the heavy part.
  4. .NET 8 minimal API → Lambda with the Amazon.Lambda.AspNetCoreServer package.
  5. Go worker that drains SQS → Lambda with an SQS event source mapping; no polling loop to write.
  6. PHP Laravel queued jobs → often stay on EC2/ECS; use Lambda for S3 event hooks and webhooks.

6. Lab: Hello from the Lambda console

Region: ap-south-1 (Mumbai). You need an AWS account. No laptop tools required.

  1. Open AWS Console → search Lambda → Functions → Create function.
  2. Choose Author from scratch. Function name: hello-lambda-lab.
  3. Runtime: Python 3.12 (or the newest Python 3.x shown). Architecture: x86_64.
  4. Permissions: leave Create a new role with basic Lambda permissions. Why: Lambda needs a role to write logs to CloudWatch.
  5. Click Create function. Wait until the code editor loads.
  6. Replace the handler body with:
def lambda_handler(event, context):
    name = (event or {}).get("name", "world")
    return {"statusCode": 200, "body": f"hello, {name}"}
  1. Click Deploy. Why: edits are not live until you deploy.
  2. Tab Test → Create new event → name hello-event → event JSON:
{"name": "Ravi"}
  1. Save → Test. Expected: statusCode 200 and body hello, Ravi, plus a green success box with duration and billed duration.
  2. Open Monitor → View CloudWatch logs. Open the newest log stream. You should see START, your print/return, END, REPORT.
  3. Configuration → General configuration → Edit. Set Timeout to 10 seconds and Memory to 256 MB. Save. Why: the default 3 s is tight for real work; 128 MB is often slow for imports.

Cleanup

  1. Lambda → Functions → select hello-lambda-lab → Actions → Delete. Confirm.
  2. IAM → Roles → delete the role named like hello-lambda-lab-role-... if it is unused.

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.

A function works once, then forgets a saved value.

An execution environment may be reused, but it is not permanent storage and different concurrent invocations can use different environments. Keep durable business records in an appropriate external store. Use local caches only for data you can safely reconstruct.

More memory is assumed to always waste money.

Memory also affects available CPU, so duration can change when memory changes. Compare measured duration, memory usage and total cost for the same workload rather than comparing the memory number alone. Do not promise that either the smallest or largest setting is always cheapest.

A network timeout is treated as proof that the timeout setting is too short.

First identify the dependency and its network path. Attaching Lambda to a public subnet does not give it a public IP or automatic internet access. A longer timeout cannot repair a missing route, blocked connection or unavailable dependency.

Practical FAQ: decisions during real work

Does serverless mean I no longer own application reliability?

No. AWS manages the underlying compute service, but you still own input validation, permissions, dependency behavior, monitoring and recovery design. A function returning normally does not prove that the user’s intended business operation completed.

Why can a retry create a second order?

The first attempt may have completed a write before its response was lost. A retry can repeat that write unless the operation uses a stable business identifier and an idempotent design. Treat an uncertain response as uncertain, not as proof that nothing happened.

Which evidence helps distinguish a slow cold start from slow handler work?

Compare the invocation report and application timing. Init Duration relates to environment initialization; handler Duration and dependency timing describe other work. Do not label every slow request a cold start just because the service is Lambda.

7. Interview questions

Q. What is AWS Lambda?

A serverless compute service. You upload a function; AWS runs it when an event arrives and charges per request and duration.

Q. Function vs trigger vs event?

Function = your code. Trigger = what starts it (S3, API Gateway, EventBridge…). Event = the JSON payload for that run.

Q. Max timeout?

30 minutes (1,800 seconds) for an on-demand Lambda Event Function. Eligible asynchronous and event source mapping invocations on Lambda Managed Instances have a separate 90-minute ceiling.

Q. Lambda vs EC2 in one line?

Lambda: no servers to manage, scales to zero, short tasks. EC2: you manage the OS, long-running and special hardware.

Q. What is the free tier?

1 million requests and 400,000 GB-seconds per month.

Q. Why does Lambda need an execution role?

The function assumes that IAM role to call AWS APIs such as writing CloudWatch Logs or reading S3. Without it, even logging fails.

Try at home

  1. Create the Hello function again in Node.js 20.x with the same test event.
  2. Change memory from 128 to 1024 MB and compare billed duration for the same event.

In short

  1. Serverless = you do not manage servers; AWS does.
  2. Lambda runs your function only when an event arrives.
  3. Pay for requests + GB-seconds; free tier covers many labs.
  4. On-demand Event Functions: up to 30 minutes and 10,240 MB memory. Direct API or console ZIP upload supports up to 50 MB compressed, with a 250 MB uncompressed package limit including layers.
  5. Use Lambda for short event-driven work; EC2/containers for long or special needs.

Practise this chapter

Check your understanding

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

0 of 3 answered correctly
1. A Lambda handler must remember a saved order between independent invocations. Which plan is reliable?

Answer and explanation

B. Store it in an appropriate durable service

Execution environments may be reused but are not durable storage. Persistent application state needs a separate service.

2. Which combination estimates the compute usage of a series of Lambda invocations?

Answer and explanation

B. Memory in GB times duration in seconds times invocation count

This gives GB-seconds for the example. Requests, data transfer and other services can add their own costs.

3. In the synchronous bakery calculator, what does the caller observe?

Answer and explanation

B. The handler’s result or an error for its invocation

A synchronous caller waits for the outcome. The handler runs inside an execution environment using the supplied event.

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

Paris Fashion Hub is a fashion business in Paris. Camille Laurent looks after its IT and cloud work. They count money in EUR and run their AWS resources in the eu-west-3 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-3.

  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 parisfashion-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 Change timeout and memory

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

Set parisfashion-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.

Medium Follow logs live

aws logs tail --follow is like tail -f for CloudWatch Logs.

Follow the log group /aws/lambda/parisfashion-orders-fn live.

  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 Create a Lambda function

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

Create function parisfashion-orders-fn: runtime python3.12, handler app.handler, role arn:aws:iam::121178088922: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=parisfashion-orders on parisfashion-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 parisfashion-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:eu-west-3:121178088922:parisfashion-orders to parisfashion-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 parisfashion-orders-fn so s3.amazonaws.com can call lambda:InvokeFunction from bucket arn:aws:s3:::parisfashion-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: What is AWS Lambda?. A bakery open all night with no customers still pays rent. Always-on servers waste money the same way. Lambda runs your code only when an event happens. You pay for requests and duration, not idle hours. Write a small function, set a runtime and role, then add a trigger (S3, API Gateway, schedule…). Photo uploaded to S3 → Lambda makes a thumbnail in seconds → idle again.
Revision card: What is AWS Lambda? · Download PNG · Open card page
Revision card: Function, trigger and event. Three words sound the same in class. Clear names stop confusion in the console. Function = your code. Trigger = what starts it. Event = the JSON payload it receives. Open any function → Configuration → Triggers. Test with a sample event JSON. API Gateway POST /orders → Lambda gets method, path and body in the event.
Revision card: Function, trigger and event · Download PNG · Open card page
Lambda vs EC2 vs containers. Use an event-driven function for bounded work. On-demand Event Functions can run up to 30 minutes per invocation. EC2 gives OS control. ECS and EKS manage container workloads, including services that keep running. Resize an image on upload with Lambda. Run a continuous worker, GPU task or hours-long job on a suitable worker platform.
Revision card: Lambda vs EC2 vs containers · Download PNG · Open card page
Lambda limits and cost. Configure up to 1,800 seconds (30 minutes), and 128–10,240 MB memory. Check the trigger and account quotas separately. A ZIP upload via console or API has a 50 MB compressed limit. Unzipped contents including layers are limited to 250 MB. A 256 MB function running for one second uses 0.25 GB-seconds. Check request charges, duration, the current allowance, and connected services.
Revision card: Lambda limits and cost · Download PNG · Open card page
Comparison: AWS Lambda vs Amazon EC2. AWS Lambda: You upload code; AWS runs and scales it. Amazon EC2: You pick, patch and size a virtual server.
Comparison: AWS Lambda vs Amazon EC2 · Download PNG · Open card page
Lambda vs containers. A Lambda Event Function accepts a ZIP or container image and runs per event. The on-demand invocation limit is 30 minutes. ECS or EKS can manage long-running services and workers. A Lambda image still follows Lambda runtime and invocation limits. Pick a bounded event handler for Lambda. Consider a service or worker for long-lived processes and custom runtime needs.
Comparison: Lambda vs containers · Download PNG · Open card page
Interview card: What does serverless mean if servers still exist?. Servers still run your code, but AWS owns patching, scaling and capacity. You focus on functions and events, not OS updates at 2 AM. Example: Lambda scales with S3 uploads; you never SSH to add boxes.
Interview card: What does serverless mean if servers still exist? · Download PNG · Open card page
When would you choose EC2 over Lambda?. Use an on-demand Event Function for bounded events up to 30 minutes. Validate the trigger's own limits. Choose EC2 or another worker platform for GPU jobs, custom OS needs, or tasks that outlast the suitable Lambda invocation mode. For an hours-long GPU training job, Lambda can accept a request and start a separate job. Return a job ID and report progress separately.
Interview card: When would you choose EC2 over Lambda? · Download PNG · Open card page
Interview card: What is a Lambda execution role?. An IAM role the function assumes so it can call AWS APIs. Without it, even CloudWatch Logs writes fail. Least privilege to only needed actions. Attach AWSLambdaBasicExecutionRole first; add S3/DynamoDB policies only if needed.
Interview card: What is a Lambda execution role? · Download PNG · Open card page
Interview card: How is Lambda billed?. Per request plus GB-seconds: memory setting × duration. Idle time is not billed like EC2. Cold starts still count as duration. Raise memory if CPU-bound; wall time often drops and can cost less.
Interview card: How is Lambda billed? · Download PNG · Open card page

More cards: Ravi Sir's Cards.