MeWrite Docs

AWS Lambda: Task timed out (Cold Start)

Lambda Cold Startタイムアウトの解決方法

概要

Lambdaのコールドスタート時に初期化が長くタイムアウトする問題です。

エラーメッセージ

Task timed out after 3.00 seconds

原因

  1. コールドスタート: 新規コンテナの起動時間
  2. 依存関係の読み込み: 大きなライブラリ
  3. VPC設定: ENI作成時間
  4. メモリ不足: CPU割り当てが低い

解決策

1. メモリを増やす

1
2
3
4
5
6
# SAM template
MyFunction:
  Type: AWS::Serverless::Function
  Properties:
    MemorySize: 1024  # 512 -> 1024
    Timeout: 30

2. Provisioned Concurrency

1
2
3
AutoPublishAlias: live
ProvisionedConcurrencyConfig:
  ProvisionedConcurrentExecutions: 5

3. 初期化を最適化

1
2
3
4
5
6
7
8
// ハンドラー外で初期化(コンテナ再利用時に共有)
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event) => {
  // dynamodbはすでに初期化済み
  return await dynamodb.get({...}).promise();
};

4. Lambda Layersでパッケージ分離

1
2
3
4
5
6
7
8
9
Layers:
  - !Ref MyDependenciesLayer

MyDependenciesLayer:
  Type: AWS::Serverless::LayerVersion
  Properties:
    ContentUri: layers/
    CompatibleRuntimes:
      - nodejs18.x

5. VPCなしで実行(可能な場合)

1
# VpcConfig を削除

よくある間違い

  • メモリとCPU比例を理解していない
  • グローバル変数での初期化忘れ

AWS の他のエラー

最終更新: 2025-12-09