AWS Lambda ও Serverless

লেসন ৩৪ / ৩৮

⚡ Serverless

  • Code only, AWS runs
  • Pay per request + execution
  • Free: 1M req + 400k GB-sec/month FOREVER

🚀 Lambda Basics

Runtime: Node, Python, Java, Go, .NET, custom
Memory: 128MB - 10GB
Timeout: 15 min max
Cold start: 100-500ms

📝 Hello Lambda (Python)

def lambda_handler(event, context):
    name = event.get("queryStringParameters",{}).get("name","World")
    return {
        "statusCode": 200,
        "body": f"Hello, {name}!"
    }

🔌 Triggers

  • API Gateway — HTTP
  • S3 — file upload event
  • EventBridge — schedule/event
  • SQS/SNS — queue/topic
  • DynamoDB Stream

🌐 API Gateway + Lambda

HTTP API → Route GET /hello → Lambda
URL: https://abc.execute-api.region.amazonaws.com/hello
Configure CORS if browser call

📦 Layers

mkdir python && pip install requests -t python/
zip -r layer.zip python
aws lambda publish-layer-version --layer-name libs \
  --zip-file fileb://layer.zip

❄️ Cold Start

Solutions:
- Provisioned concurrency (paid)
- ARM64 arch (faster+cheap)
- Smaller package
- Connection reuse OUTSIDE handler
- Python/Node (not Java/.NET)

# Reuse pattern
import boto3
s3 = boto3.client("s3")   # outside — warm

def handler(event, ctx):
    s3.list_buckets()

🛠️ Serverless Framework

npm i -g serverless

# serverless.yml
service: my-api
provider:
  name: aws
  runtime: python3.12

functions:
  hello:
    handler: handler.lambda_handler
    events:
      - httpApi: GET /hello

serverless deploy

🔥 SAM (AWS native)

# template.yaml
Transform: AWS::Serverless-2016-10-31
Resources:
  HelloFn:
    Type: AWS::Serverless::Function
    Properties:
      Handler: handler.lambda_handler
      Runtime: python3.12
      Events:
        Api:
          Type: HttpApi
          Properties: {Path: /hello, Method: GET}

sam build && sam deploy --guided

⚠️ Not Use When

  • Long running >15 min
  • High constant traffic (EC2 cheaper)
  • Latency-critical <10ms p99
  • Steady WebSocket

💰 Pricing

Request: $0.20/1M
Compute: $0.0000166667/GB-sec
Free: 1M req + 400k GB-sec ALWAYS

100k req/mo, 256MB, 200ms = $0 (free tier)

🎓 মূল কথা ⭐

Lambda brilliant for event-driven, sporadic, glue code। Always-on heavy = EC2 cheaper। Free tier huge — small API $0।