☁️ Cloud

AWS Lambda

AWS's serverless computing service

📖 Detailed Explanation

AWS Lambda is a serverless compute service that lets you run code without provisioning or managing servers. When you upload your code, AWS automatically manages the infrastructure and runs the code only when requests come in. You are billed only for execution time (in milliseconds) and memory usage.

Launched at re:Invent in 2014, Lambda is a pioneer that popularized the "serverless" paradigm. Initially it supported only Node.js, but it now supports a variety of runtimes such as Python, Java, Go, .NET, and Ruby, as well as container images. 1 million requests and 400,000 GB-seconds of compute time per month are free under the free tier.

Lambda is a core component of event-driven architecture. Events from more than 200 AWS services can be used as triggers, including S3 file uploads, DynamoDB streams, API Gateway requests, SQS messages, and EventBridge schedules. It can run for up to 15 minutes, memory ranges from 128MB to 10GB, and vCPUs are allocated automatically in proportion to memory.

In practice, Lambda is used for a variety of purposes, such as API backends, file processing, data transformation, scheduled jobs, and real-time stream processing. Recently, Lambda SnapStart improved Java cold starts by 90%, and edge computing is also supported through Lambda@Edge and CloudFront Functions.

💻 Code Example

# Lambda 핸들러 함수 예제 (Python)
import json
import boto3
import logging
from datetime import datetime

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

# Lambda 컨테이너 재사용 시 연결 유지 (콜드 스타트 최적화)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('users')

def lambda_handler(event, context):
    """
    API Gateway에서 호출되는 Lambda 핸들러
    event: API Gateway 이벤트 객체
    context: Lambda 실행 컨텍스트 (요청 ID, 남은 시간 등)
    """
    logger.info(f"Request ID: {context.aws_request_id}")
    logger.info(f"Remaining time: {context.get_remaining_time_in_millis()}ms")

    try:
        # API Gateway 이벤트 파싱
        body = json.loads(event.get('body', '{}'))
        user_id = event['pathParameters']['userId']

        # DynamoDB 조회
        response = table.get_item(Key={'userId': user_id})

        if 'Item' not in response:
            return {
                'statusCode': 404,
                'headers': {'Content-Type': 'application/json'},
                'body': json.dumps({'error': 'User not found'})
            }

        return {
            'statusCode': 200,
            'headers': {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*'
            },
            'body': json.dumps(response['Item'], default=str)
        }

    except Exception as e:
        logger.error(f"Error: {str(e)}")
        return {
            'statusCode': 500,
            'body': json.dumps({'error': 'Internal server error'})
        }


# 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']

        logger.info(f"Processing: s3://{bucket}/{key}")

        # 파일 처리 로직...
        # 예: 이미지 리사이즈, 데이터 변환 등

    return {'processed': len(event['Records'])}

🗣️ Say It Like This in Practice

💬 In Architecture Design
"This API has unpredictable call volume and spikes instantly to 1000 TPS at peak times, so Lambda is a good fit. If you're worried about cold starts, you can pre-warm about 10 instances with Provisioned Concurrency, and based on expected traffic, costs should be reduced by about 60% compared to EC2."
💬 In an Interview
"I have experience designing and operating Lambda-based serverless architectures. I built a REST API using a combination of API Gateway + Lambda + DynamoDB, and built an asynchronous processing pipeline by integrating SQS with Lambda. To optimize cold starts, I chose Node.js over Python and applied the pattern of initializing DB connections outside the handler."
💬 In Troubleshooting
"The Lambda concurrent execution limit is 1000 and we're using all of it right now, so throttling is occurring. Let's first set Reserved Concurrency on the critical functions, and buffer the less important functions through SQS to regulate processing speed. In the long term, we should also request an account limit increase."

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

⚠️ Common Mistakes & Cautions

❌
Design That Ignores Cold Starts

Lambda terminates the container if there are no requests for a certain period of time. When it starts again, a cold start occurs (Node.js 100-200ms, Python 200-400ms, Java 2-5 seconds). For latency-sensitive APIs, use Provisioned Concurrency or enable SnapStart (Java).

❌
Initializing Resources Inside the Handler

If you create DB connections and SDK clients inside the handler function, they are initialized on every invocation. If you create them only once in the global scope, they are reused on a warm start, which greatly improves performance.

✅
The right approach

Using the ARM64 (Graviton2) architecture improves price-performance by up to 34% compared to x86. Increasing memory also increases vCPUs proportionally, so allocate enough memory for CPU-bound workloads. 1 vCPU is allocated at 1,769MB.

🔗 Related Terms

📚 Learn More