πŸ’‘ Ask Tutor

Serverless Computing with AWS Lambda

Run Code Without Servers β€” Automatically Scalable and Event-Driven

AWS Lambda is at the heart of serverless architectureβ€”it allows developers to run backend code without provisioning or managing servers. You just write the function, deploy it, and AWS handles the rest: scalability, availability, and infrastructure.

This chapter provides deep insights, real use cases, architecture diagrams, and live code examples in Python and Node.js.


⚑ What is AWS Lambda?

AWS Lambda is a compute service that runs your code in response to events and automatically manages the underlying infrastructure.

  • No servers to manage
  • You pay only for the compute time you consume
  • Automatically scales from zero to thousands of requests per second
  • Supports multiple runtimes: Python, Node.js, Java, Go, .NET

🧱 Key Concepts in Lambda

TermDescription
FunctionThe code you upload or write inline
EventThe trigger (e.g., HTTP request, S3 upload)
HandlerThe function entry point (e.g., lambda_handler)
RuntimeLanguage environment (e.g., Python 3.9)
TimeoutMax execution time (up to 15 mins)
MemoryAdjustable from 128MB to 10GB (affects CPU)
ConcurrencyNumber of simultaneous executions
Cold StartInitial latency when Lambda starts a new container

How AWS Lambda Works – Architecture Diagram (ASCII)

LESS
    [Event Source]
        (S3 / API Gateway / DynamoDB / Schedule)
               ↓
         +-------------+
         |  AWS Lambda |
         +-------------+
               ↓
      [Your Code Executes]
               ↓
    [Other AWS Services or Response]

Common Event Sources (Triggers)

SourceExample Use Case
S3Process image upload, resize
API GatewayBackend for web/mobile apps
CloudWatch EventsScheduled cron jobs
DynamoDB StreamsReact to DB changes
SQSQueue processing
SNSNotification-based triggers
Step FunctionsServerless workflows

βœ… AWS supports dozens of event sources, both native and third-party.

Creating a Lambda Function (Console & CLI)

βœ… Using Console (Quick Steps):

  1. Go to AWS Lambda β†’ Create function
  2. Choose Author from Scratch
  3. Name: image-processor
  4. Runtime: Python 3.9
  5. Permissions: Create a new role with S3 access
  6. Click Create Function
  7. Add code + test event
  8. Save and Deploy

βœ… Using AWS CLI

Bash
zip function.zip index.py

aws lambda create-function \
  --function-name my-function \
  --runtime python3.9 \
  --role arn:aws:iam::123456789012:role/my-lambda-role \
  --handler index.lambda_handler \
  --zip-file fileb://function.zip

Example Lambda Code

πŸ”Έ Python (Resizing an Image in S3)

Python
import boto3
from PIL import Image
import io

def lambda_handler(event, context):
    s3 = boto3.client('s3')
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = event['Records'][0]['s3']['object']['key']

    response = s3.get_object(Bucket=bucket, Key=key)
    image = Image.open(response['Body'])

    image.thumbnail((128, 128))
    buffer = io.BytesIO()
    image.save(buffer, 'JPEG')
    buffer.seek(0)

    s3.put_object(Bucket=bucket, Key=f"thumbs/{key}", Body=buffer)
    return {"status": "Thumbnail created"}

πŸ”Ή Node.js (Return JSON API Response)

JavaScript
exports.handler = async (event) => {
  return {
    statusCode: 200,
    body: JSON.stringify({ message: "Hello from Lambda!" }),
  };
};

Lambda Layers – Reusable Code and Libraries

Layers are ZIP archives of libraries or dependencies that can be shared across Lambda functions.

  • Use for: Python packages (e.g., Pandas), image libraries, Node.js modules
  • Speeds up deployment & promotes reuse
Bash
aws lambda publish-layer-version \
  --layer-name my-layer \
  --zip-file fileb://layer.zip \
  --compatible-runtimes python3.9

Lambda Limits (as of 2025)

FeatureLimit
Timeout15 minutes
Memory128MB – 10GB
Package size (zip)50MB (direct) / 250MB (with S3)
Concurrency (default)1000 per account (can increase)
Environment variables4KB

🧠 Use Provisioned Concurrency to reduce cold start latency.

Monitoring Lambda Functions

ToolWhat It Shows
CloudWatch Logsstdout + error logs
CloudWatch MetricsInvocations, Duration, Errors, Throttles
X-RayTrace execution path
Lambda InsightsMemory usage, CPU, execution details

βœ… Always enable logs and metrics for production functions.

πŸ” Security & Permissions

  • Lambda assumes an IAM Role to access resources (e.g., S3, DynamoDB)
  • Follow least privilege when creating the role
  • Use environment variables + KMS for secrets
  • Set VPC access only if required (adds latency)

βœ… Real-World Use Cases

IndustryUse Case
E-commerceOrder processing (event-driven)
Media/PublishingImage/video conversion
SaaS PlatformsAPI backend without managing servers
IoTSensor event processing
AnalyticsReal-time ETL pipelines with Kinesis + Lambda
DevOpsAuto-stop EC2s, monitor events, automate cleanups

Best Practices

PracticeWhy It Matters
Use short timeoutsPrevent hanging functions
Keep package size smallReduces cold start
Use layers for dependenciesCode reuse and manageability
Monitor throttling & retriesTo avoid data loss
Avoid infinite loopsCosts can spike fast
Use async handlersBetter performance with APIs
Implement dead-letter queues (DLQ)To catch failed invocations

Summary

FeatureDescription
ServerlessNo servers to manage
Pay-per-executionBilled by usage (ms)
Event-drivenTriggered by S3, API Gateway, Cron, etc.
Multi-languagePython, Node.js, Java, Go, .NET
Fast scaling1000s of requests per second
ObservabilityCloudWatch, X-Ray, Lambda Insights
SecurityIAM roles, VPC control, encrypted env vars