AWS Lambda サーバーレスベストプラクティス
AWS Lambda関数のベストプラクティス: コールドスタート最適化、冪等性パターン、IAM最小権限、Powertoolsによる構造化ログ、CDK v2。
# AWS Lambda Best Practices
This guide outlines the definitive best practices for developing AWS Lambda functions. Adhere to these principles to build reliable, cost-effective, and secure serverless applications.
## Code Organization and Structure
**1. Single Responsibility Principle:** Each Lambda function must perform one distinct task. Decompose complex workflows into smaller, focused functions orchestrated by services like AWS Step Functions.
**2. Initialize Outside the Handler:** Leverage execution environment reuse by initializing SDK clients, database connections, and heavy dependencies in the global scope.
Good:
```python
import boto3
s3 = boto3.client('s3') # Initialized once per execution environment
def handler(event, context):
# s3 client is reused across invocations
pass
```
Bad:
```python
def handler(event, context):
s3 = boto3.client('s3') # Initialized on every invocation
pass
```
**3. Use Lambda Layers for Shared Code:** Keep deployment packages small and promote code reuse for common libraries and dependencies.
**4. Configuration via Environment Variables:** Never hardcode operational parameters. Use environment variables for dynamic configuration. For sensitive data, use AWS Secrets Manager or AWS Systems Manager Parameter Store.
**5. Structured JSON Logging:** Output logs in JSON format to CloudWatch using `aws-lambda-powertools` Logger utility.
```python
from aws_lambda_powertools import Logger
logger = Logger()
@logger.inject_lambda_context
def handler(event, context):
logger.info("Processing event", event=event)
```
**6. Infrastructure as Code (AWS CDK v2):** Define Lambda functions and surrounding infrastructure using AWS CDK v2.
## Common Patterns and Anti-patterns
**1. Implement Idempotency:** Design functions to produce the same result even if invoked multiple times with the same input. Use `aws-lambda-powertools` for robust idempotency.
```python
from aws_lambda_powertools.utilities.idempotency import idempotent
from aws_lambda_powertools.utilities.idempotency.persistence import DynamoDBPersistenceLayer
import os
persistence_layer = DynamoDBPersistenceLayer(table_name=os.environ["IDEMPOTENCY_TABLE"])
@idempotent(persistence_layer=persistence_layer)
def handler(event, context):
# Process order, guaranteed to run once
pass
```
**2. Stateless Functions:** Functions must not rely on mutable local state between invocations. Any mutable data belongs in external, durable storage (e.g., DynamoDB, S3).
**3. Orchestrate with Step Functions:** For complex, multi-step workflows, use AWS Step Functions. Keep individual Lambda functions simple.
## Performance Considerations
**1. Optimize Memory and CPU:** Memory allocation directly impacts CPU. Use the AWS Lambda Power Tuning tool to find the optimal memory configuration.
**2. Keep Deployment Packages Small:** Minimize cold start times by reducing package size. Use Lambda Layers and only include necessary dependencies.
## Security Best Practices
**1. Over-privileged IAM Roles:** Apply the principle of least privilege.
Bad:
```json
{"Effect": "Allow", "Action": "s3:*", "Resource": "*"}
```
Good:
```json
{"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject"], "Resource": "arn:aws:s3:::my-specific-bucket/*"}
```
**2. Lack of Input Validation:** Always validate and sanitize all incoming event data. Use libraries like Pydantic or `aws-lambda-powertools` Parser utility.
**3. Recursive Invocations:** Avoid functions calling themselves directly or indirectly, as this can lead to infinite loops and escalated costs.
## Testing Approaches
**1. Unit Testing:** Test the core business logic in isolation, mocking AWS service interactions.
**2. Integration Testing:** Test function interactions with actual AWS services using ephemeral resources.
**3. Local Development:** Utilize AWS SAM CLI or LocalStack to test functions locally before deployment. こちらもおすすめ
cloud カテゴリの他のルール
もっとルールを探す
CLAUDE.md、.cursorrules、AGENTS.md、Image Prompts の全 223 ルールをチェック。



