Understanding Serverless Computing with AWS Lambda: A Practical Guide for Modern Developers

5.59K 0 0 0 0

📘 Chapter 3: Writing and Deploying Lambda Functions

🔍 Overview

At the core of AWS Lambda is the function itself — a small unit of code designed to run on-demand. This chapter focuses on writing Lambda functions in supported languages, understanding the function handler structure, using environment variables, managing dependencies, and deploying using multiple methods such as the console, CLI, container images, and popular frameworks like SAM and Serverless Framework.


️ 1. Lambda Function Basics

Components of a Lambda Function

Component

Description

Handler

The entry point method of the function

Runtime

Execution environment (e.g., Node.js, Python)

Trigger

Event that invokes the function

Execution role

IAM permissions assigned to the function

Environment variables

Runtime configs like API keys or DB connections

Logs

Captured via CloudWatch


🧠 2. Writing Your First Function

Let’s look at basic Lambda function examples in different languages.

Node.js Example

javascript

 

exports.handler = async (event) => {

    console.log("Event received:", JSON.stringify(event));

    return {

        statusCode: 200,

        body: JSON.stringify({ message: "Hello from Node.js Lambda!" })

    };

};


Python Example

python

 

def lambda_handler(event, context):

    print("Event:", event)

    return {

        "statusCode": 200,

        "body": "Hello from Python Lambda!"

    }


Java Example

java

 

public class HelloLambda implements RequestHandler<Map<String,String>, String> {

    public String handleRequest(Map<String,String> event, Context context) {

        return "Hello from Java Lambda!";

    }

}


🧪 3. Using Environment Variables

Environment variables are key-value pairs that let you configure functions without hardcoding values.

Set via Console or CLI

bash

 

aws lambda update-function-configuration \

  --function-name MyFunction \

  --environment "Variables={DB_HOST=db.example.com,DB_PORT=3306}"

Access in Code

  • Node.js: process.env.DB_HOST
  • Python: os.environ['DB_HOST']

📦 4. Managing Dependencies

If your function uses external libraries, package them along with your function code.

Node.js

bash

 

npm init -y

npm install axios

zip -r function.zip index.js node_modules/

Python

bash

 

pip install requests -t .

zip -r function.zip lambda_function.py requests/

You can also use Lambda Layers to reuse packages across functions.


🚀 5. Deployment Methods

Lambda supports multiple deployment approaches depending on your development workflow.


A. Console Deployment (for quick tests)

  • Ideal for simple logic
  • Not recommended for large functions or version control

B. ZIP File Deployment (CLI)

bash

 

zip function.zip index.js

aws lambda update-function-code \

  --function-name MyFunction \

  --zip-file fileb://function.zip


C. Container Image Deployment

  1. Create Dockerfile

Dockerfile

 

FROM public.ecr.aws/lambda/nodejs:18

COPY app.js package.json ./

RUN npm install

CMD ["app.handler"]

  1. Build & Push Image

bash

 

docker build -t my-lambda-image .

aws ecr create-repository --repository-name my-lambda-repo

docker tag my-lambda-image:latest <ECR_URI>

docker push <ECR_URI>

  1. Deploy Function

bash

 

aws lambda create-function \

  --function-name MyContainerLambda \

  --package-type Image \

  --code ImageUri=<ECR_URI> \

  --role arn:aws:iam::123456789012:role/LambdaExecutionRole


D. AWS SAM (Serverless Application Model)

Template Example (template.yaml):

yaml

 

AWSTemplateFormatVersion: '2010-09-09'

Transform: AWS::Serverless-2016-10-31

Resources:

  HelloWorldFunction:

    Type: AWS::Serverless::Function

    Properties:

      Handler: index.handler

      Runtime: nodejs18.x

      CodeUri: .

      MemorySize: 128

      Timeout: 5

Deploy:

bash

 

sam build

sam deploy --guided


E. Serverless Framework

serverless.yml:

yaml

 

service: hello-lambda

provider:

  name: aws

  runtime: nodejs18.x

functions:

  hello:

    handler: handler.hello

Deploy:

bash

 

sls deploy


🔄 6. Versioning and Aliases

  • Lambda supports function versions for immutability
  • Aliases act as pointers to versions (e.g., dev, prod)

bash

 

aws lambda publish-version --function-name MyFunction

aws lambda create-alias --function-name MyFunction \

  --name prod --function-version 2


🔍 7. Debugging and Logging

Use CloudWatch Logs to view logs from your function.

Log Access via CLI

bash

 

aws logs filter-log-events \

  --log-group-name /aws/lambda/MyFunction

Log inside your handler:

  • Node.js: console.log()
  • Python: print()
  • Java: System.out.println()

🧠 8. Best Practices

  • Keep functions small and focused
  • Use environment variables for secrets/configs
  • Use layers for shared dependencies
  • Implement timeouts and error handling
  • Keep your code stateless
  • Log input/output for debugging
  • Use SAM or Serverless Framework for scalable deployments

📋 Summary Table – Writing and Deploying Lambda


Step

Method

Write Function

Console, VS Code, IDE

Package Dependencies

Local folder, ZIP, Docker, or Layer

Deploy

Console, CLI, SAM, Serverless Framework

Set Environment Vars

CLI, Console, IaC tools

Versioning

publish-version, create-alias

Monitor Logs

CloudWatch or aws logs CLI

Back

FAQs


❓1. What is AWS Lambda?

Answer:
AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. You upload your function code, define a trigger (like an API call or S3 event), and AWS runs it automatically, scaling as needed and billing only for the time your code runs.

❓2. What languages are supported by AWS Lambda?

Answer:
Lambda natively supports Node.js, Python, Java, Go, .NET (C#), Ruby, and custom runtimes (via Lambda extensions) for any Linux-compatible language including Rust and PHP.

❓3. How long can a Lambda function run?

Answer:
The maximum execution timeout for a Lambda function is 15 minutes (900 seconds). If your function exceeds this time, it will be terminated automatically.

❓4. What is a cold start in Lambda?

Answer:
A cold start occurs when Lambda has to initialize a new execution environment for a function, usually after a period of inactivity or for the first call. It can introduce slight latency (milliseconds to seconds), especially in VPC or Java/.NET-based functions.

❓5. Is AWS Lambda always running?

Answer:
No. Lambda is event-driven—it runs your code only when triggered by an event (like an HTTP request, a scheduled timer, or an S3 upload). It’s dormant the rest of the time, which helps reduce costs.

❓6. Can Lambda functions connect to a database?

Answer:
Yes, Lambda can connect to databases like RDS, DynamoDB, Aurora, and even external systems. For VPC-based databases, you must configure the Lambda function with proper VPC settings and security group access.

❓7. How do I deploy my code to Lambda?

Answer:
You can deploy your code by:

  • Uploading a ZIP file via the AWS Console or CLI
  • Using the AWS SAM (Serverless Application Model)
  • Deploying Docker images from Amazon ECR
  • Using frameworks like Serverless Framework or Terraform

❓8. What are Lambda function triggers?

Answer:
Triggers are AWS services or events that invoke your function. Common examples include

  • API Gateway (HTTP requests)
  • S3 (file uploads)
  • DynamoDB Streams (table changes)
  • EventBridge (scheduled jobs)
  • SNS/SQS (messages)

❓9. How is AWS Lambda priced?

Answer:
Lambda pricing is based on:

  • Number of requests: $0.20 per 1 million requests
  • Duration: Measured in milliseconds, based on memory allocation (128 MB to 10 GB)
    A generous free tier includes 1M free requests/month and 400,000 GB-seconds of compute time.

❓10. Can Lambda be used to build full applications?

Answer:
Yes, many modern applications are built using Lambda + API Gateway + DynamoDB or similar stacks. It supports use cases like REST APIs, scheduled tasks, data pipelines, and IoT event processing—but you must architect with stateless, short-lived, and event-driven patterns.