HomeBlogAboutPricingContact🌐 δΈ­ζ–‡
← Back to HomeAWS
AWS Lambda Getting Started Guide: Serverless Computing Tutorial, Pricing, Use Cases [2025]

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

πŸ“‘ Table of Contents

AWS Lambda Getting Started Guide: Serverless Computing Tutorial, Pricing, Use Cases [2025]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?

πŸ’‘ Key Takeaway: 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:

Not ideal for Lambda:

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:



Lambda Core Concepts

Functions and Execution Environment

Lambda Function is the code you upload, containing:

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

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:

Memory and Timeout Configuration

Memory

Timeout

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:

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

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

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

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:

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:

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:

Triggerable Events:

Implementation example: AWS S3 Complete Tutorial

EventBridge (CloudWatch Events)

Scheduled execution or triggered by AWS service events.

Use Cases:

Schedule Examples:

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:

DynamoDB Streams

Triggers when DynamoDB table changes occur.

Application β†’ Writes to DynamoDB β†’ Stream β†’ Lambda

Use Cases:

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:

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:

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": "CloudSwap"
  }
}
  1. Click "Test" to execute
  2. View execution result:
{
  "statusCode": 200,
  "headers": {
    "Content-Type": "application/json"
  },
  "body": "{\"message\": \"Hello, CloudSwap!\"}"
}

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:



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:

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

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

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)

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

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 CloudSwap 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:

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:

How does Lambda access VPC resources?

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



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 CloudSwap 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



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

AWSAzureKubernetesDocker
← Previous
AWS Lambda Pricing Complete Guide: Free Tier, Billing Model & Cost-Saving Tips [2025]
Next β†’
AWS vs GCP vs Azure 2025 Complete Comparison: Features, Pricing, Pros & Cons