MeWrite Docs

Task timed out after X.00 seconds

AWS LambdaでタイムアウトしてTask timed outとなるエラー

概要

AWS Lambda関数が設定されたタイムアウト時間内に実行を完了できなかった場合に発生するエラーです。デフォルトのタイムアウトは3秒、最大15分まで設定可能です。

エラーメッセージ

Task timed out after 3.00 seconds
1
2
3
{
  "errorMessage": "2023-01-01T00:00:00.000Z xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx Task timed out after 3.00 seconds"
}

原因

  1. 処理時間超過: 処理が設定時間より長くかかる
  2. 外部API呼び出し: 外部サービスのレスポンスが遅い
  3. データベース接続: DB接続のタイムアウトや遅延
  4. コールドスタート: 初回起動時の遅延
  5. 無限ループ: 終了しないループ処理
  6. メモリ不足: メモリ不足による処理速度低下

解決策

1. タイムアウト時間を延長

1
2
3
4
5
# serverless.yml
functions:
  myFunction:
    handler: handler.main
    timeout: 30  # 30秒に延長
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# AWS CDK
from aws_cdk import aws_lambda as lambda_
from aws_cdk import Duration

my_function = lambda_.Function(
    self, "MyFunction",
    runtime=lambda_.Runtime.PYTHON_3_11,
    handler="handler.main",
    code=lambda_.Code.from_asset("lambda"),
    timeout=Duration.seconds(30)
)

2. メモリを増やす(CPUも比例して増加)

1
2
3
4
5
6
# serverless.yml
functions:
  myFunction:
    handler: handler.main
    memorySize: 1024  # 1GB
    timeout: 30

3. 外部API呼び出しにタイムアウト設定

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import requests

def handler(event, context):
    try:
        response = requests.get(
            'https://api.example.com/data',
            timeout=5  # 5秒でタイムアウト
        )
        return response.json()
    except requests.Timeout:
        return {'error': 'External API timeout'}

4. コネクションプールを再利用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import boto3

# ハンドラ外で初期化(コールドスタート時のみ実行)
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('MyTable')

def handler(event, context):
    # 再利用される
    response = table.get_item(Key={'id': event['id']})
    return response['Item']

5. 非同期処理に変更

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 同期処理が長い場合、Step Functionsやキューを使用

import boto3
import json

sqs = boto3.client('sqs')

def handler(event, context):
    # 長い処理はキューに投げる
    sqs.send_message(
        QueueUrl='https://sqs.region.amazonaws.com/xxx/my-queue',
        MessageBody=json.dumps(event)
    )
    return {'statusCode': 202, 'body': 'Processing started'}

6. 残り時間を確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def handler(event, context):
    # 残り時間を確認
    remaining_time = context.get_remaining_time_in_millis()

    for item in large_list:
        if context.get_remaining_time_in_millis() < 1000:  # 1秒未満
            # 処理を中断してキューに戻すなど
            return {'status': 'incomplete', 'last_processed': item}
        process(item)

    return {'status': 'complete'}

7. Provisioned Concurrencyでコールドスタート回避

1
2
3
4
5
# serverless.yml
functions:
  myFunction:
    handler: handler.main
    provisionedConcurrency: 5

8. VPC設定の見直し

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# VPC内のLambdaはENI作成に時間がかかる
functions:
  myFunction:
    handler: handler.main
    vpc:
      securityGroupIds:
        - sg-xxxxxxxx
      subnetIds:
        - subnet-xxxxxxxx
    timeout: 60  # VPC内は長めに設定

監視とデバッグ

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import logging
import time

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

def handler(event, context):
    start = time.time()
    logger.info(f"Start processing: {event}")

    # 処理
    result = do_something()

    elapsed = time.time() - start
    logger.info(f"Elapsed time: {elapsed:.2f}s")
    logger.info(f"Remaining time: {context.get_remaining_time_in_millis()}ms")

    return result

よくある間違い

  • 同期的に大量のAPI呼び出しを行う
  • VPC内LambdaでNAT Gateway経由の遅延を考慮しない
  • コールドスタートの影響を見落とす
  • メモリを増やすとCPUも増えることを知らない

関連エラー

参考リンク

AWS の他のエラー

最終更新: 2025-12-13