AWS SDK for Python (Boto3)の エラーの再試行について

AWS SDK for Python (Boto3)の エラーの再試行について

Clock Icon2018.10.14

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

API 呼び出しは様々な要因で一時的に失敗することがありますが、AWS SDKは自動再試行ロジックを実装しています。今回は、AWS SDK for Python (Boto3)でのリトライ回数の変更方法をご紹介します。

リトライ処理やエクスポネンシャルバックオフについてはAWSドキュメント AWS でのエラーの再試行とエクスポネンシャルバックオフ もご参照ください。

Boto3におけるリトライ処理、エクスポネンシャルバックオフ

自動でリトライ処理が実装されていますが、AWS SDK for Python (Boto3)ではデフォルトで5回エクスポネンシャルバックオフによるリトライ処理が実施されるようです。

Boto 3 Documentation | Config Referenceより

'max_attempts' -- An integer representing the maximum number of retry attempts that will be made on a single request. For example, setting this value to 2 will result in the request being retried at most two times after the initial request. Setting this value to 0 will result in no retries ever being attempted on the initial request. If not provided, the number of retries will default to whatever is modeled, which is typically four retries.

_retry.jsonより

例)

"retry": {
  "__default__": {
    "max_attempts": 5,
    "delay": {
      "type": "exponential",
      "base": "rand",
      "growth_factor": 2
    },

リトライ数を変更する

セッションやサービスクライアントを作成時に config (botocore.client.Config)retriesを設定することで変更することが可能です。

session作成時のconfigにretriesを設定する

例) メソッド呼び出しの最大リトライ数を10に設定する

from boto3.session import Session
from botocore.client import Config


session = Session()
config = Config(
    retries=dict(
        max_attempts=10
    )
)
client = session.client('ec2', config=config)

client作成時のconfigにretriesを設定する

例)メソッド呼び出しの最大リトライ数を10に設定する

import boto3
from botocore.config import Config


config = Config(
    retries=dict(
        max_attempts=10
    )
)
client = boto3.client('ec2', config=config)

まとめ

エクスポネンシャルバックオフはとても重要なアルゴリズムです。今回は、AWS SDK for Python (Boto3)についてご紹介しましたが、AWS SDKを使用していない場合などにもエクスポネンシャルバックオフアルゴリズムを取り入れたリトライ処理を実装することをおすすめします。 Pythonだと、retryingというモジュールがあります。

参考URL

この記事をシェアする

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.