Back to HomeAWS

AWS Lambda Getting Started Guide: Serverless Computing Tutorial, Pricing, Use Cases [2025]

14 min min read

AWS Lambda Getting Started Guide: Serverless Computing Tutorial, Pricing, Use Cases [2025]

AWS Lambda Getting Started Guide: Serverless Computing Tutorial, Pricing, Use Cases [2025]

Don't want to manage servers? Use Lambda. Upload your code, AWS runs it. No requests, no charges. With requests, it auto-scales to thousands of concurrent executions. 1 million requests per month are free, and beyond that it's just $0.20 per million.

This article will introduce you to Lambda—what it is, how it's priced, what languages it supports, and step-by-step instructions to create your first Lambda function.


What is AWS Lambda?

Lambda is AWS's serverless compute service. You just upload your code, and Lambda automatically runs it when there are requests, releasing resources when done.

What "Serverless" Means

"Serverless" doesn't mean there are no servers—it means you don't manage them.

AspectTraditional (EC2)Serverless (Lambda)
Server ManagementYou set up and maintainAWS handles everything
ScalingManual or configure Auto ScalingAutomatic, no configuration needed
BillingInstance runtimeActual execution milliseconds
Idle CostYes (charges even with no traffic)None (no requests, no charges)
Capacity PlanningNeed to estimate trafficNot needed

How Lambda Works

Trigger Event → Lambda Starts Container → Runs Your Code → Returns Result → Releases Resources
     │                    │                     │                │
     │              (Cold Start)         (Billing Starts)  (Billing Ends)
     │
HTTP Request, S3 Upload, Schedule, Message Queue...

Lambda uses AWS's own container technology Firecracker (also used in Fargate) behind the scenes, capable of starting execution environments in milliseconds.

When Should You Use Lambda?

Good fit for Lambda:

  • Event-driven tasks (file upload processing, webhooks)
  • API backends (with API Gateway)
  • Scheduled tasks (daily cron jobs)
  • Data processing pipelines
  • Chatbot backends

Not ideal for Lambda:

  • Long-running programs (over 15 minutes)
  • Applications requiring persistent connections (WebSocket servers)
  • Applications with extreme low-latency requirements
  • Machine learning training requiring GPUs

Lambda vs EC2: How to Choose?

ConsiderationChoose LambdaChoose EC2
Execution Time< 15 minutesPotentially long
Request PatternVariable, with peaksSteady, continuous
Operations CapabilityDon't want to manage serversHave ops capability
Cost ConsiderationLow or variable request volumeSustained high load
Special RequirementsNoneNeed GPU, special hardware

Rule of thumb:

  • If monthly execution is < 1 million GB-seconds, Lambda is usually cheaper
  • If load is steady with high CPU utilization, EC2 Reserved may be more cost-effective

Lambda Core Concepts

Functions and Execution Environment

Lambda Function is the code you upload, containing:

  • Handler: The entry point function
  • Code: Your business logic
  • Dependencies: Required libraries

Execution Environment is the container Lambda uses to run your code, containing:

  • Operating system (Amazon Linux 2)
  • Runtime (e.g., Python 3.12, Node.js 20)
  • Your code and dependencies

Supported Programming Languages

Lambda natively supports these runtimes:

RuntimeVersionsNotes
Node.js18.x, 20.x, 22.xMost popular choice
Python3.9, 3.10, 3.11, 3.12Common for data processing
Java11, 17, 21Enterprise applications
.NET6, 8C# developers
Go1.xHigh-performance needs
Ruby3.2, 3.3Ruby developers
RustVia Custom RuntimeMaximum performance

Using other languages:

  • Custom Runtime: Any language works
  • Container Image: Package as Docker image

Memory and Timeout Configuration

Memory

  • Range: 128 MB - 10,240 MB
  • CPU performance scales with memory (1,769 MB ≈ 1 vCPU)
  • More memory = higher price

Timeout

  • Range: 1 second - 15 minutes
  • Exceeding timeout forces termination
  • Set a reasonable timeout to avoid infinite waits

Configuration Recommendations:

ScenarioMemoryTimeout
Simple API responses256-512 MB10 seconds
Data processing1024-2048 MB1-5 minutes
Image processing2048-3008 MB1-3 minutes
ML inference4096-10240 MB1-5 minutes

Concurrent Execution (Concurrency)

Lambda can handle multiple requests simultaneously, each in an independent execution environment.

Default concurrency limit: 1,000 (can request increase)

Reserved Concurrency: Reserve concurrency quota for specific functions

Provisioned Concurrency: Pre-warm execution environments to avoid cold starts

Cold Start

When there's no ready execution environment, Lambda needs to start a new one—this is called a "cold start."

Cold start times:

  • Node.js/Python: ~200-500ms
  • Java/.NET: ~1-3 seconds
  • Container Image: ~1-5 seconds

Reducing cold start impact:

  1. Use lighter runtimes (Node.js, Python)
  2. Reduce deployment package size
  3. Use Provisioned Concurrency (paid)
  4. Keep functions "warm" (periodic invocations)

Lambda Pricing Model

Lambda billing is very granular—you only pay for actual execution time.

Billing Components

Lambda Cost = Request Fee + Compute Fee + (Provisioned Concurrency Fee)

Request Fees

Each Lambda invocation counts as one request.

Price: $0.20 / million requests

Free Tier: 1 million requests per month free

Compute Fees

Billed by "GB-seconds"—memory size multiplied by execution time.

Price: $0.0000166667 / GB-second

Free Tier: 400,000 GB-seconds per month free

Calculation:

GB-seconds = (Memory MB / 1024) × Execution Time (seconds)
Cost = GB-seconds × Unit Price

Cost Calculation Examples

Scenario 1: Lightweight API

  • 5 million requests per month
  • Memory 256 MB
  • Average execution time 100ms
Request Fee = (5,000,000 - 1,000,000) × $0.0000002 = $0.80
GB-seconds = 5,000,000 × 0.25 GB × 0.1 seconds = 125,000 GB-seconds
Compute Fee = (125,000 - 400,000) = 0 (within free tier)
Total ≈ $0.80/month

Scenario 2: Data Processing

  • 1 million requests per month
  • Memory 1024 MB
  • Average execution time 2 seconds
Request Fee = 0 (within free tier)
GB-seconds = 1,000,000 × 1 GB × 2 seconds = 2,000,000 GB-seconds
Compute Fee = (2,000,000 - 400,000) × $0.0000166667 = $26.67
Total ≈ $26.67/month

Scenario 3: High-Traffic API

  • 100 million requests per month
  • Memory 512 MB
  • Average execution time 200ms
Request Fee = (100,000,000 - 1,000,000) × $0.0000002 = $19.80
GB-seconds = 100,000,000 × 0.5 GB × 0.2 seconds = 10,000,000 GB-seconds
Compute Fee = (10,000,000 - 400,000) × $0.0000166667 = $160.00
Total ≈ $179.80/month

Provisioned Concurrency Fees

If you need to avoid cold starts, use Provisioned Concurrency:

Additional cost: $0.000004646 / GB-second (continuous billing)

For 512 MB with 10 Provisioned Concurrency:

  • Per hour: 0.5 × 10 × 3600 × $0.000004646 = $0.084
  • Monthly about $60

Typically used only in latency-sensitive scenarios.


Lambda Triggers

Lambda is event-driven and needs "triggers" to start execution.

API Gateway

The most common trigger method, turning Lambda into an HTTP API.

User → HTTP Request → API Gateway → Lambda → Response

Use Cases:

  • RESTful APIs
  • GraphQL APIs
  • Webhook receivers

Setup:

  1. Create API Gateway (REST or HTTP API)
  2. Create routes and methods
  3. Select Lambda as backend integration
  4. Deploy API

S3 Event

Triggers Lambda when S3 Bucket events occur (uploads, deletions).

User Uploads File → S3 → Triggers Lambda → Processes File

Use Cases:

  • Image thumbnail generation
  • File format conversion
  • Data import processing
  • Virus scanning

Triggerable Events:

  • s3:ObjectCreated:* (any creation)
  • s3:ObjectCreated:Put (PUT upload)
  • s3:ObjectCreated:Post (POST upload)
  • s3:ObjectRemoved:* (any deletion)

Implementation example: AWS S3 Complete Tutorial

EventBridge (CloudWatch Events)

Scheduled execution or triggered by AWS service events.

Use Cases:

  • Scheduled tasks (daily backups, hourly cleanups)
  • AWS service event reactions (EC2 state changes)
  • Custom event buses

Schedule Examples:

  • rate(5 minutes): Every 5 minutes
  • rate(1 hour): Every hour
  • cron(0 8 * * ? *): Every day at 8 AM

SQS / SNS

Triggered from message queues or notification services.

SQS (Simple Queue Service):

Producer → SQS Queue → Lambda (batch processing)

SNS (Simple Notification Service):

Publisher → SNS Topic → Lambda (fan-out)

Use Cases:

  • Asynchronous task processing
  • Decoupling system components
  • Batch processing large message volumes

DynamoDB Streams

Triggers when DynamoDB table changes occur.

Application → Writes to DynamoDB → Stream → Lambda

Use Cases:

  • Data sync to other systems
  • Trigger downstream workflows
  • Build search indexes

Other Triggers

TriggerUse Case
KinesisReal-time streaming data processing
CognitoUser authentication events
CloudFrontEdge computing (Lambda@Edge)
IoTIoT device events
AlexaVoice assistant skills

Lambda Creation Tutorial

Here are complete steps to create your first Lambda function.

Step 1: Log into AWS Console

  1. Go to AWS Console
  2. Search for "Lambda" and click to enter

Step 2: Create Function

  1. Click "Create function"
  2. Select "Author from scratch"

Basic Information:

  • Function name: my-first-lambda
  • Runtime: Python 3.12
  • Architecture: x86_64

Permissions:

  • Select "Create a new role with basic Lambda permissions"
  1. Click "Create function"

Step 3: Write Code

In the Code source section, you'll see the default Hello World program:

import json

def lambda_handler(event, context):
    return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')
    }

Parameter explanation:

  • event: Data from the trigger event (e.g., HTTP request content)
  • context: Execution environment info (remaining time, memory, etc.)

Modify to a practical example:

import json

def lambda_handler(event, context):
    # Get request parameters
    name = event.get('queryStringParameters', {}).get('name', 'World')

    # Processing logic
    message = f'Hello, {name}!'

    # Return result
    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'application/json'
        },
        'body': json.dumps({
            'message': message
        })
    }

Click "Deploy" to save changes.

Step 4: Test Function

  1. Click the "Test" tab
  2. Create test event:
{
  "queryStringParameters": {
    "name": "CloudInsight"
  }
}
  1. Click "Test" to execute
  2. View execution result:
{
  "statusCode": 200,
  "headers": {
    "Content-Type": "application/json"
  },
  "body": "{\"message\": \"Hello, CloudInsight!\"}"
}

Step 5: Configure Trigger (API Gateway)

  1. Click "Add trigger"
  2. Select "API Gateway"
  3. Choose:
    • API type: HTTP API
    • Security: Open
  4. Click "Add"

After completion, you'll get an API endpoint URL that can be tested directly in browser:

https://xxxxx.execute-api.us-east-1.amazonaws.com/default/my-first-lambda?name=Test

Step 6: View Monitoring

In the Monitor tab you can see:

  • Invocations (call count)
  • Duration (execution time)
  • Errors (error count)
  • Throttles (throttle count)

Lambda Use Cases

Image Processing

User uploads image to S3, Lambda automatically generates thumbnails.

Architecture:

User → S3 (uploads/) → Lambda → S3 (thumbnails/)

Code Example (Python):

import boto3
from PIL import Image
import io

s3 = boto3.client('s3')

def lambda_handler(event, context):
    # Get uploaded file info
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = event['Records'][0]['s3']['object']['key']

    # Download original image
    response = s3.get_object(Bucket=bucket, Key=key)
    image = Image.open(io.BytesIO(response['Body'].read()))

    # Generate thumbnail
    image.thumbnail((200, 200))

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

    thumbnail_key = key.replace('uploads/', 'thumbnails/')
    s3.put_object(Bucket=bucket, Key=thumbnail_key, Body=buffer)

    return {'statusCode': 200}

API Backend

Build REST API with API Gateway.

Architecture:

Frontend → API Gateway → Lambda → DynamoDB

Advantages:

  • No server management
  • Auto-scaling
  • Pay only for actual requests

Scheduled Tasks

Daily scheduled tasks.

Example: Clean up expired data daily

EventBridge schedule: cron(0 3 * * ? *) (every day at 3 AM)

import boto3
from datetime import datetime, timedelta

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('sessions')

def lambda_handler(event, context):
    # Calculate expiry time (7 days ago)
    expiry = datetime.now() - timedelta(days=7)

    # Scan and delete expired data
    response = table.scan(
        FilterExpression='created_at < :expiry',
        ExpressionAttributeValues={':expiry': expiry.isoformat()}
    )

    for item in response['Items']:
        table.delete_item(Key={'session_id': item['session_id']})

    return {'deleted': len(response['Items'])}

Data Processing Pipeline

Process uploaded CSV files, transform and store in database.

Architecture:

User Uploads CSV → S3 → Lambda → Process Data → DynamoDB

Lambda Best Practices

Performance Optimization

1. Reduce Deployment Package Size

  • Include only necessary dependencies
  • Use Lambda Layers to share dependencies
  • Consider lighter runtimes (like Python)

2. Reuse Connections

# Initialize outside handler for reuse
import boto3
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('my-table')

def lambda_handler(event, context):
    # Use already-initialized connection
    table.put_item(Item={...})

3. Choose Appropriate Memory

  • More memory = more CPU
  • Sometimes more memory is actually cheaper (faster execution)

Error Handling

1. Use Structured Logging

import json
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)

def lambda_handler(event, context):
    logger.info(json.dumps({
        'event': 'processing_started',
        'request_id': context.aws_request_id
    }))

2. Set Up Dead Letter Queue (DLQ)

  • Failed events won't be lost
  • Can be reprocessed or analyzed later

3. Implement Retry Logic

import time

def call_external_api(retry=3):
    for attempt in range(retry):
        try:
            # Call external API
            return response
        except Exception as e:
            if attempt < retry - 1:
                time.sleep(2 ** attempt)  # Exponential backoff
            else:
                raise

Security

1. Principle of Least Privilege

  • Only give Lambda the IAM permissions it needs
  • Avoid using * wildcards

2. Use Environment Variables for Secrets

import os
api_key = os.environ['API_KEY']

3. Enable VPC (if accessing private resources)

Advanced configuration: AWS VPC Tutorial

Is serverless architecture right for you? Let experts help evaluate

Lambda isn't a silver bullet. When to use Lambda, when to use EC2, when to use containers? This depends on your specific requirements.

The CloudInsight team has extensive Serverless architecture experience. Schedule a free consultation and let us design the optimal architecture for you.


FAQ

Can Lambda connect to databases?

Yes. But manage connections carefully:

  • Use RDS Proxy to avoid too many connections
  • DynamoDB is a better fit for Lambda (HTTP connections)
  • Consider Aurora Serverless

How do I solve Lambda cold starts?

  1. Choose lighter runtimes (Python, Node.js)
  2. Reduce dependency package size
  3. Use Provisioned Concurrency (paid)
  4. Periodically invoke to keep "warm" (unofficial approach)

Can Lambda run longer than 15 minutes?

No. If tasks need more time:

  • Split into multiple Lambdas (coordinate with Step Functions)
  • Use EC2 or Fargate instead
  • Use AWS Batch

How does Lambda access VPC resources?

Configure VPC, subnets, and security groups in Lambda settings. But note:

  • Cold start time increases
  • Need NAT Gateway to access internet
  • Consider VPC Endpoints for AWS service access

Next Steps

Lambda opens the door to serverless architecture. Master Lambda and you can build more flexible, cost-effective cloud applications.

Recommended Learning Path:

  1. Hands-on: Build a simple API (API Gateway + Lambda + DynamoDB)
  2. Event-driven: Set up S3 to trigger Lambda for file processing
  3. Scheduled tasks: Use EventBridge to run Lambda on schedule
  4. Advanced: Learn Step Functions to coordinate multiple Lambdas

Need help with Serverless architecture planning?

From Lambda function design, trigger selection to cost optimization, Serverless architecture has many details to consider. The CloudInsight team has helped multiple enterprises design and optimize serverless architectures.

Schedule a free architecture consultation and let us plan the optimal Serverless solution for you.


Further Reading


Illustration: Serverless Concept Comparison

Scene Description: Serverless concept comparison diagram. Left side shows traditional architecture (server icons user must manage, labeled "You Manage"), right side shows Lambda architecture (only code icon, server portion labeled "AWS Manages"). Center divided by dotted line emphasizing responsibility boundary. Clean icon style.

Visual Focus:

  • Main content clearly presented

Required Elements:

  • Key elements as described

Required Text: None

Color Scheme: Professional, clear

Avoid: Abstract graphics, gears, glowing effects

Slug: lambda-serverless-concept

Illustration: Lambda Pricing Calculator

Scene Description: Lambda pricing calculation diagram. Formula visualized: Requests × Unit Price + GB-seconds × Unit Price = Total Cost. Below shows three example scenarios (Lightweight API, Data Processing, High-Traffic API) with actual calculations. Emphasizes Free Tier allowances.

Visual Focus:

  • Main content clearly presented

Required Elements:

  • Key elements as described

Required Text: None

Color Scheme: Professional, clear

Avoid: Abstract graphics, gears, glowing effects

Slug: lambda-pricing-calculator


Need Professional Cloud Advice?

Whether you're evaluating cloud platforms, optimizing existing architecture, or looking for cost-saving solutions, we can help

Book Free Consultation

Related Articles