倚
Duoyun Cloud
← Back to Blog
tutorials2026-04-17

AWS Lambda Beginner Guide with Node.js Examples

AWSLambdaServerlessNode.js

AWS Lambda Beginner Guide with Node.js Examples

If you are looking for a way to run code without managing servers, AWS Lambda is one of the most mature serverless computing platforms available today. This tutorial will guide you from zero to building and deploying your first Lambda function using Node.js, with deep dives into core concepts and real-world scenarios.

What Is AWS Lambda?

AWS Lambda is an event-driven serverless computing service provided by AWS. You simply upload your code, and Lambda automatically handles provisioning, scaling, and fault tolerance of the underlying infrastructure. You pay only for the actual compute time β€” billed at 1ms granularity.

Key Benefits:

  • Zero Operations: No servers, OS, or runtime environments to manage
  • Automatic Scaling: From a few requests per day to thousands per second, automatically
  • Pay-per-use: Only pay for actual compute time; idle time costs nothing
  • Multi-language: Node.js, Python, Java, Go, .NET, and more

Pricing Overview

AWS Lambda offers a free tier of 1 million free requests per month and 400,000 GB-seconds of compute time. Beyond that:

| Billing Item | Price | |--------------|-------| | Per million requests | $0.20 | | Compute (per GB-second) | $0.0000166667 | | 128MB memory, 100ms execution | ~$0.0000002083 |

Prerequisites

Before starting, make sure you have the following:

  1. AWS Account: Sign up for the AWS free tier
  2. Node.js 18.x+: LTS version recommended
  3. AWS CLI: Installed and configured with aws configure
  4. AWS SAM CLI (optional): For local debugging
# Install AWS CLI
brew install awscli

# Configure credentials
aws configure
# Enter Access Key ID, Secret Access Key, Region (e.g., us-east-1)

# Verify
aws sts get-caller-identity

Your First Lambda Function: Hello World

Option 1: AWS Console

  1. Log in to the AWS Management Console and navigate to the Lambda service
  2. Click "Create function"
  3. Select "Author from scratch"
  4. Configure:
    • Function name: hello-world
    • Runtime: Node.js 20.x
    • Architecture: x86_64
    • Execution role: Create a new role
  5. Click "Create function"

Option 2: Write the Code

Replace the default index.mjs with the following code:

export const handler = async (event) => {
  console.log('Event:', JSON.stringify(event, null, 2));

  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      message: 'Hello from AWS Lambda!',
      timestamp: new Date().toISOString(),
    }),
  };
};

Click "Deploy changes", then click "Test" to create a test event and run the function.

Practical Example: RESTful API Handler

Let us build a more practical example β€” an API function handling CRUD operations:

// handler.mjs
const users = new Map();
let nextId = 1;

export const handler = async (event) => {
  const { httpMethod, path, body, pathParameters } = event;
  const headers = {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
  };

  try {
    switch (httpMethod) {
      case 'GET': {
        if (pathParameters?.id) {
          const user = users.get(pathParameters.id);
          if (!user) {
            return { statusCode: 404, headers, body: JSON.stringify({ error: 'User not found' }) };
          }
          return { statusCode: 200, headers, body: JSON.stringify(user) };
        }
        return {
          statusCode: 200,
          headers,
          body: JSON.stringify(Array.from(users.values())),
        };
      }

      case 'POST': {
        const data = JSON.parse(body);
        const id = String(nextId++);
        const user = { id, ...data, createdAt: new Date().toISOString() };
        users.set(id, user);
        return { statusCode: 201, headers, body: JSON.stringify(user) };
      }

      case 'DELETE': {
        if (pathParameters?.id) {
          users.delete(pathParameters.id);
          return { statusCode: 204, headers, body: '' };
        }
        return { statusCode: 400, headers, body: JSON.stringify({ error: 'Missing user id' }) };
      }

      default:
        return { statusCode: 405, headers, body: JSON.stringify({ error: 'Method not allowed' }) };
    }
  } catch (error) {
    return { statusCode: 500, headers, body: JSON.stringify({ error: error.message }) };
  }
};

Integrating with API Gateway

To make your Lambda function accessible via HTTP, configure API Gateway:

  1. In the Lambda console, click "Add trigger"
  2. Select "API Gateway"
  3. Choose "Create a new API" β†’ REST API
  4. Set security to "Open" (for test environments only)
  5. Click "Add"

After deployment, you will receive a URL like:

https://abc123.execute-api.us-east-1.amazonaws.com/prod/hello-world

Deploying with SAM Template

For production environments, Infrastructure as Code (IaC) deployment is recommended. Here is a SAM template example:

# template.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  ApiFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: src/
      Handler: handler.handler
      Runtime: nodejs20.x
      MemorySize: 256
      Timeout: 10
      Events:
        GetUsers:
          Type: Api
          Properties:
            Path: /users
            Method: GET
        CreateUser:
          Type: Api
          Properties:
            Path: /users
            Method: POST
        GetUser:
          Type: Api
          Properties:
            Path: /users/{id}
            Method: GET

Deploy commands:

# Build
sam build

# Local testing
sam local start-api

# Deploy (first-time guided setup)
sam deploy --guided

Performance Optimization Tips

| Strategy | Description | Effect | |----------|-------------|--------| | Cold Start Optimization | Use Provisioned Concurrency | Reduce 50-90% cold start latency | | Memory Tuning | Increment from 128MB to optimal point | Double memory β†’ halve execution time | | Connection Reuse | Initialize DB connections outside handler | Avoid rebuilding connections per invocation | | Layers | Package shared dependencies as Layers | Reduce deployment package size | | Node.js ES Modules | Use .mjs format | Faster module loading |

Monitoring and Logging

Lambda integrates automatically with Amazon CloudWatch:

  • Logs: console.log() output goes to CloudWatch Logs automatically
  • Metrics: Invocations, error rate, duration, concurrent executions
  • X-Ray Tracing: Visualize request paths when enabled
// Structured logging example
export const handler = async (event) => {
  const startTime = Date.now();

  try {
    const result = await processEvent(event);
    console.log(JSON.stringify({
      level: 'INFO',
      message: 'Request processed',
      duration: Date.now() - startTime,
      requestId: event.requestContext?.requestId,
    }));
    return result;
  } catch (error) {
    console.error(JSON.stringify({
      level: 'ERROR',
      message: error.message,
      stack: error.stack,
    }));
    throw error;
  }
};

Best Practices and Caveats

  1. Keep functions stateless: Lambda instances may be reclaimed at any time; do not rely on local storage
  2. Control deployment package size: Trim node_modules, bundle with Webpack/esbuild
  3. Set reasonable timeouts: Default is 3 seconds, maximum is 15 minutes
  4. Use environment variables: Store secrets in AWS Secrets Manager, config items as env vars
  5. Design for idempotency: The same event may be retried; ensure your function is idempotent

Conclusion

AWS Lambda + Node.js is a powerful combination for building modern serverless applications. From simple HTTP APIs to complex event processing pipelines, Lambda provides a flexible and cost-effective solution. The key is understanding core concepts like cold starts, memory configuration, and the event-driven model.

Want better pricing on AWS? Purchase AWS resources through Duoyun Cloud and enjoy partner-exclusive discounts, saving up to 25% on cloud spending. Visit duoyun.io to learn more.

Need Professional Cloud Consulting?

Our cloud architect team will customize the best solution for you β€” free

Free Consultation

Related Posts

news

AWS reInvent 2025 Key Announcements for Enterprises

2026-04-23
news

Sovereign Cloud and Data Residency Regulations 2026

2026-04-23
optimization

AWS Spot Instance Strategies for Batch Processing

2026-04-22