Introduction To Aws Lambda

Introduction To Aws Lambda

Reading time1 min
#Cloud#Serverless#Computing#AWSLambda#ServerlessComputing#AWS

Getting Started with AWS Lambda: A Hands-On Walkthrough

Managing idle EC2 instances for sporadic workloads is a known cost (and operational) headache. With AWS Lambda, engineers can offload a swath of short-lived logic—notifications, REST endpoints, ETL pipelines—without provisioning or patching infrastructure. Lambda abstracts servers entirely, exposing a simple event-driven execution model: write function, upload, set trigger, done.


AWS Lambda in Practice

Lambda is Amazon’s core Function-as-a-Service (FaaS) offering. It executes code on-demand, scaling per-invocation and billing exclusively per request and execution time. Supported runtimes (as of May 2024) include Python 3.12, Node.js 20.x, Java 21, .NET 8, Go 1.x, and custom runtimes via Lambda Extensions.

Typical Event Sources

  • API Gateway: HTTP endpoints, synchronous (REST, HTTP APIs).
  • S3: Object creation or deletion triggers.
  • DynamoDB Streams: React to data mutations.
  • CloudWatch Events/Scheduled (cron): Automated jobs.

Notably, over 200+ AWS services emit events suitable for Lambda. Integration is tightly coupled.


Anatomy of a Lambda Function

At minimum, a Lambda deployment consists of:

  • Handler code (e.g., lambda_function.py)
  • Specified runtime/runtime version
  • Trigger configuration
  • IAM permissions (beware: excessive privileges = risk vector)

Example: Minimal HTTP Responder in Python 3.12

def lambda_handler(event, context):
    return {
        "statusCode": 200,
        "body": "Hello from AWS Lambda"
    }

Event shape varies by trigger; API Gateway delivers standard REST event payloads, S3 passes notification record batches, etc.

Known issue: Cold starts on infrequently used functions can add 200–900 ms to invocation. For latency-sensitive endpoints, consider provisioned concurrency (extra cost).


Implementation: Deploy a Lambda-backed API Endpoint

Prerequisites

  • AWS account (root/mfa recommended for setup, least privilege IAM for deploy)
  • AWS CLI v2+ (aws --version to confirm)
  • Python 3.12 installed locally (if testing code)

1. Author Your Function

Create lambda_function.py as above.

2. Create Lambda in AWS Console

  1. Navigate: AWS Console → Lambda → Create function
  2. Author from scratch:
    • Name: HelloWorldFunction
    • Runtime: Python 3.12
    • Execution role: Create a new role with basic Lambda permissions
  3. Create function

Replace sample code with your handler. Press Deploy.

3. Add an API Gateway Trigger

Under Triggers:

  • Add trigger → API Gateway
    • Create API: HTTP API (simpler for basic scenarios)
    • Security: Open (demo only—production should require authorizer/JWT)

Caution: Any open API endpoint may be scraped by bots. For production, set up IAM auth, a Lambda authorizer, or JWT validation.

4. Test Your Endpoint

Find invoke URL (e.g., https://abcdef1234.execute-api.us-east-1.amazonaws.com/default/HelloWorldFunction).
Invoke:

curl https://abcdef1234.execute-api.us-east-1.amazonaws.com/default/HelloWorldFunction

Expected output:

{"statusCode": 200, "body": "Hello from AWS Lambda"}

Real-world glitch: If you see {"message": "Internal server error"}, open CloudWatch Logs to inspect stack traces. Common causes:

  • Handler syntax error
  • Omitted return value
  • Missing permissions for underlying resources

Observability & Troubleshooting

Lambda automatically emits stdout/stderr to CloudWatch Logs under /aws/lambda/<functionName>. For structured traces, include:

import logging
logger = logging.getLogger()
logger.info("processing event: %r", event)

Monitor duration, error rate, and cold starts via Lambda Insights.


Trade-Offs and Practical Notes

  • Ephemeral disk (/tmp, up to 512 MB): Useful for temp files—cleared between invocations unless container re-use occurs.
  • Timeout: Hard cap of 15 minutes per invocation.
  • Package size: Max 50 MB zipped via direct upload, 250 MB uncompressed if linked to S3.
  • Concurrent executions: Account-level default limit varies (~1000); request quota increases when needed.
  • Alternative: For heavy compute (ML inference, video processing), consider AWS Fargate or ECS for longer-lived containers.

Side note: There’s no native outbound static IP; use VPC + NAT Gateway for fixed egress, with added latency.


Beyond Hello World

  • Add input validation (reject large payloads or invalid structure).
  • Use environment variables for configuration.
  • Integrate with SNS/SQS for decoupling event sources.
  • Layers: Share dependencies (e.g., requests, numpy) across functions.
  • Automate deployment: AWS SAM, Serverless Framework, Terraform official aws_lambda_function resource.
  • Enable X-Ray tracing for distributed context.

Summary

Lambda enables production-grade event-driven workflows, REST APIs, and automation at scale—with minimal operational overhead. Deployed wisely, it reduces cost and risk, but there are trade-offs: cold starts, package limits, and IAM complexity require careful design consideration. For one-off jobs and unpredictable workloads, nothing comes close.

Non-obvious tip: Use the Lambda Power Tuning tool to empirically select optimal memory size for your function—higher memory yields more CPU, affecting both speed and cost. Don’t just pick 128MB by default.


References

              +-----------------+     triggers    +---------------------+
Event Source-->|   AWS Lambda   |---------------->|   Target Resource   |
              +-----------------+                 +---------------------+

If you hit edge-cases, check CloudWatch logs first—the error messages aren’t always obvious. For persistence or low-latency connections, revisit architectural assumptions.