☁️ Cloud

Lambda

AWS Lambda / Serverless Functions

AWS serverless computing. Billed only for code execution. Event-driven.

📖 Detailed Explanation

AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. You are billed only for the time your code runs (in 100ms increments), and it automatically scales up to thousands of requests per second. It is a representative FaaS (Function as a Service) offering.

It integrates with various AWS services through trigger mechanisms. Synchronous invocation: receives HTTP requests from API Gateway or ALB and responds immediately. Asynchronous invocation: triggered by S3 events, SNS, or EventBridge for background processing. Stream-based: processes records in batches from Kinesis and DynamoDB Streams. Polling-based: fetches and processes messages from SQS.

The execution environment supports a variety of runtimes. Node.js, Python, Java, Go, .NET, Ruby, and even custom runtimes (Rust, C++, etc.) are possible. Memory is 128MB~10GB, the timeout is up to 15 minutes, and the package size is 250MB (50MB when compressed). You can separate common libraries with Lambda Layers, and run containers of up to 10GB with Container Image.

Cold Start is an important characteristic of Lambda. If there are no invocations for a certain period of time, the execution environment is terminated and is initialized anew on the next invocation. This delay is the Cold Start. Using Provisioned Concurrency lets you prepare the execution environment in advance and eliminate Cold Starts, but it incurs additional cost.

💻 Code Example

# handler.py - API Gateway + DynamoDB 연동
import json
import boto3
import os
from datetime import datetime
from decimal import Decimal

# 함수 밖에서 초기화 (Cold Start 최적화)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table(os.environ['TABLE_NAME'])

def lambda_handler(event, context):
    """
    API Gateway에서 호출되는 Lambda 핸들러
    """
    try:
        # HTTP 메서드별 처리
        http_method = event['httpMethod']

        if http_method == 'GET':
            return get_items(event)
        elif http_method == 'POST':
            return create_item(event)
        elif http_method == 'PUT':
            return update_item(event)
        elif http_method == 'DELETE':
            return delete_item(event)
        else:
            return response(405, {'error': 'Method not allowed'})

    except Exception as e:
        print(f"Error: {str(e)}")
        return response(500, {'error': 'Internal server error'})

def get_items(event):
    """전체 조회 또는 단일 조회"""
    path_params = event.get('pathParameters') or {}
    item_id = path_params.get('id')

    if item_id:
        # 단일 조회
        result = table.get_item(Key={'id': item_id})
        if 'Item' not in result:
            return response(404, {'error': 'Item not found'})
        return response(200, decimal_to_float(result['Item']))
    else:
        # 전체 조회 (페이지네이션)
        query_params = event.get('queryStringParameters') or {}
        limit = int(query_params.get('limit', 20))

        scan_kwargs = {'Limit': limit}
        if 'cursor' in query_params:
            scan_kwargs['ExclusiveStartKey'] = {'id': query_params['cursor']}

        result = table.scan(**scan_kwargs)
        return response(200, {
            'items': [decimal_to_float(item) for item in result['Items']],
            'cursor': result.get('LastEvaluatedKey', {}).get('id')
        })

def create_item(event):
    """새 아이템 생성"""
    body = json.loads(event['body'])

    item = {
        'id': body['id'],
        'name': body['name'],
        'created_at': datetime.utcnow().isoformat(),
        'updated_at': datetime.utcnow().isoformat()
    }

    table.put_item(
        Item=item,
        ConditionExpression='attribute_not_exists(id)'
    )

    return response(201, decimal_to_float(item))

def response(status_code, body):
    """API Gateway 응답 포맷"""
    return {
        'statusCode': status_code,
        'headers': {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Headers': 'Content-Type,Authorization',
            'Access-Control-Allow-Methods': 'GET,POST,PUT,DELETE,OPTIONS'
        },
        'body': json.dumps(body, ensure_ascii=False)
    }

def decimal_to_float(obj):
    """DynamoDB Decimal을 JSON 직렬화 가능한 타입으로 변환"""
    if isinstance(obj, Decimal):
        return float(obj)
    elif isinstance(obj, dict):
        return {k: decimal_to_float(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [decimal_to_float(i) for i in obj]
    return obj

# --- S3 이벤트 핸들러 예제 ---
def s3_handler(event, context):
    """
    S3 버킷에 파일 업로드 시 트리거
    이미지 리사이징, 메타데이터 추출 등에 사용
    """
    s3_client = boto3.client('s3')

    for record in event['Records']:
        bucket = record['s3']['bucket']['name']
        key = record['s3']['object']['key']

        print(f"Processing: s3://{bucket}/{key}")

        # 파일 처리 로직
        # ...

    return {'statusCode': 200}
// handler.js - SQS 메시지 처리 핸들러
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { DynamoDBDocumentClient, PutCommand, GetCommand } = require('@aws-sdk/lib-dynamodb');

// Cold Start 최적화: 클라이언트 재사용
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);

/**
 * SQS 메시지 배치 처리 핸들러
 * 부분 실패 시 실패한 메시지만 재처리되도록 설정
 */
exports.sqsHandler = async (event) => {
    console.log(`Processing ${event.Records.length} messages`);

    const failedMessageIds = [];

    for (const record of event.Records) {
        try {
            const body = JSON.parse(record.body);
            await processMessage(body);
            console.log(`Successfully processed: ${record.messageId}`);
        } catch (error) {
            console.error(`Failed to process: ${record.messageId}`, error);
            failedMessageIds.push(record.messageId);
        }
    }

    // 부분 배치 실패 응답 (ReportBatchItemFailures 활성화 필요)
    return {
        batchItemFailures: failedMessageIds.map(id => ({
            itemIdentifier: id
        }))
    };
};

async function processMessage(message) {
    // 비즈니스 로직
    await docClient.send(new PutCommand({
        TableName: process.env.TABLE_NAME,
        Item: {
            id: message.id,
            data: message.data,
            processedAt: new Date().toISOString()
        }
    }));
}

/**
 * API Gateway 핸들러 (ES Module 스타일)
 */
export const apiHandler = async (event, context) => {
    // 컨텍스트 재사용 설정
    context.callbackWaitsForEmptyEventLoop = false;

    const { httpMethod, path, body, queryStringParameters } = event;

    try {
        switch (httpMethod) {
            case 'GET':
                const id = event.pathParameters?.id;
                if (id) {
                    const result = await docClient.send(new GetCommand({
                        TableName: process.env.TABLE_NAME,
                        Key: { id }
                    }));

                    if (!result.Item) {
                        return formatResponse(404, { error: 'Not found' });
                    }
                    return formatResponse(200, result.Item);
                }
                // 목록 조회
                // ...
                break;

            case 'POST':
                const data = JSON.parse(body);
                // 생성 로직
                return formatResponse(201, { message: 'Created', id: data.id });

            default:
                return formatResponse(405, { error: 'Method not allowed' });
        }
    } catch (error) {
        console.error('Handler error:', error);
        return formatResponse(500, { error: 'Internal server error' });
    }
};

function formatResponse(statusCode, body) {
    return {
        statusCode,
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        },
        body: JSON.stringify(body)
    };
}

/**
 * EventBridge 스케줄 핸들러 (Cron Job)
 */
exports.scheduledHandler = async (event) => {
    console.log('Scheduled event:', JSON.stringify(event));

    // 정기 작업 실행
    // 예: 만료된 데이터 정리, 리포트 생성 등

    return { status: 'completed' };
};
# Terraform으로 Lambda 함수 배포
# main.tf

# Lambda 실행 역할
resource "aws_iam_role" "lambda_role" {
  name = "api-lambda-role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action = "sts:AssumeRole"
      Effect = "Allow"
      Principal = {
        Service = "lambda.amazonaws.com"
      }
    }]
  })
}

# DynamoDB 접근 정책
resource "aws_iam_role_policy" "lambda_policy" {
  name = "api-lambda-policy"
  role = aws_iam_role.lambda_role.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = [
          "dynamodb:GetItem",
          "dynamodb:PutItem",
          "dynamodb:UpdateItem",
          "dynamodb:DeleteItem",
          "dynamodb:Scan",
          "dynamodb:Query"
        ]
        Resource = aws_dynamodb_table.main.arn
      },
      {
        Effect = "Allow"
        Action = [
          "logs:CreateLogGroup",
          "logs:CreateLogStream",
          "logs:PutLogEvents"
        ]
        Resource = "arn:aws:logs:*:*:*"
      }
    ]
  })
}

# Lambda 함수
resource "aws_lambda_function" "api" {
  function_name = "api-handler"
  role          = aws_iam_role.lambda_role.arn
  handler       = "handler.lambda_handler"
  runtime       = "python3.11"

  filename         = "lambda.zip"
  source_code_hash = filebase64sha256("lambda.zip")

  memory_size = 256
  timeout     = 30

  environment {
    variables = {
      TABLE_NAME  = aws_dynamodb_table.main.name
      ENVIRONMENT = "production"
    }
  }

  # VPC 설정 (필요시)
  vpc_config {
    subnet_ids         = var.private_subnet_ids
    security_group_ids = [aws_security_group.lambda.id]
  }

  # X-Ray 추적 활성화
  tracing_config {
    mode = "Active"
  }

  # Provisioned Concurrency (Cold Start 제거)
  # aws_lambda_provisioned_concurrency_config 리소스로 별도 설정
}

# Lambda 함수 URL (API Gateway 대안)
resource "aws_lambda_function_url" "api" {
  function_name      = aws_lambda_function.api.function_name
  authorization_type = "NONE"  # 또는 "AWS_IAM"

  cors {
    allow_origins = ["https://example.com"]
    allow_methods = ["GET", "POST", "PUT", "DELETE"]
    allow_headers = ["Content-Type", "Authorization"]
    max_age       = 86400
  }
}

# API Gateway 연동
resource "aws_apigatewayv2_api" "api" {
  name          = "api"
  protocol_type = "HTTP"

  cors_configuration {
    allow_origins = ["*"]
    allow_methods = ["GET", "POST", "PUT", "DELETE", "OPTIONS"]
    allow_headers = ["Content-Type", "Authorization"]
  }
}

resource "aws_apigatewayv2_integration" "lambda" {
  api_id             = aws_apigatewayv2_api.api.id
  integration_type   = "AWS_PROXY"
  integration_method = "POST"
  integration_uri    = aws_lambda_function.api.invoke_arn
}

resource "aws_apigatewayv2_route" "api" {
  api_id    = aws_apigatewayv2_api.api.id
  route_key = "ANY /{proxy+}"
  target    = "integrations/${aws_apigatewayv2_integration.lambda.id}"
}

# Lambda 권한 (API Gateway에서 호출 허용)
resource "aws_lambda_permission" "api_gw" {
  statement_id  = "AllowAPIGatewayInvoke"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.api.function_name
  principal     = "apigateway.amazonaws.com"
  source_arn    = "${aws_apigatewayv2_api.api.execution_arn}/*/*"
}

# CloudWatch 로그 그룹 (보존 기간 설정)
resource "aws_cloudwatch_log_group" "lambda" {
  name              = "/aws/lambda/${aws_lambda_function.api.function_name}"
  retention_in_days = 14
}

# --- SAM template.yaml 예시 ---
# AWSTemplateFormatVersion: '2010-09-09'
# Transform: AWS::Serverless-2016-10-31
#
# Globals:
#   Function:
#     Timeout: 30
#     MemorySize: 256
#     Runtime: python3.11
#
# Resources:
#   ApiFunction:
#     Type: AWS::Serverless::Function
#     Properties:
#       Handler: handler.lambda_handler
#       CodeUri: src/
#       Events:
#         Api:
#           Type: HttpApi
#           Properties:
#             Path: /{proxy+}
#             Method: ANY

💬 How It's Used in Practice

Architecture Decision Meeting

PM: "We're debating whether to build the new API service on Lambda or ECS. Traffic averages 100 RPS, with peaks of around 1000 RPS."

DevOps: "At that traffic level, Lambda is cost-efficient. But if API response time matters, you need to consider Cold Start. If you set Provisioned Concurrency to around 50, you can handle peaks without delay. However, there is a 15-minute timeout limit per function, so for long-running tasks, split them off to Step Functions or consider ECS. Monthly cost is about $50 for Lambda versus about $200 for ECS Fargate, so Lambda has the advantage."

Interview Questions

Interviewer: "Please explain how to optimize Lambda's Cold Start."

Candidate: "There are several strategies. First, initialize SDK clients and DB connections outside the handler function so they can be reused. Second, minimize the package size and separate dependencies with Lambda Layers. Third, increasing memory also increases CPU proportionally, which speeds up initialization. Fourth, you can keep always-warmed instances with Provisioned Concurrency. Node.js has a shorter Cold Start than Python, and Go has a shorter one than Java. In practice, I have experience improving P99 latency from 2 seconds to 200ms after applying Provisioned Concurrency."

Cost Optimization Discussion

Developer: "Our Lambda costs are higher than expected. How can we reduce them?"

SRE: "First, analyze execution time and memory usage with CloudWatch Insights. If memory is over-provisioned, reduce it; conversely, sometimes increasing memory to shorten execution time is more cost-efficient. You can find the optimal memory setting with the AWS Lambda Power Tuning tool. Also, switching to the ARM64 (Graviton2) architecture is 20% cheaper for the same performance. For tasks that can be batch-processed, increase the batch size together with SQS to reduce the number of invocations."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

❌

Initializing the Client Inside the Handler Every Time

If you create an AWS SDK client or a DB connection inside the handler function, initialization cost is incurred on every invocation. If you initialize it outside the function (in global scope), you can benefit when the execution environment is reused.

❌

Not Setting a Timeout for Synchronous Invocation

When integrating API Gateway with Lambda, the Lambda timeout (up to 15 minutes) and the API Gateway timeout (up to 29 seconds) differ. If Lambda runs longer, API Gateway returns a 504, but Lambda continues to run. Set the Lambda timeout shorter than the API Gateway timeout.

✅

Enable SQS Partial Batch Failure Handling

If you enable ReportBatchItemFailures on an SQS trigger, only the failed messages are reprocessed. By default, the entire batch is retried, which can result in duplicate processing. Implement the handler to return batchItemFailures.

🔗 Related Terms

📚 Learn More