8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Python]AWS Lambdaでのリトライ処理(Exponential Backoff)のメモ

Posted at

Lambdaファンクション内でのリトライ処理ってどうしたら良いものか?と思い調べてみたメモです。

Lambdaでのリトライ処理については以下のスライドが参考になりました。

また、Exponential Backoffについては以下の記事が詳しいです。

実際に書いてみる

LambdaファンクションはAWS Chaliceで書きます。(リトライ処理はChaliceで無くても問題なくできます。)
リトライについては、以下のライブラリを利用してみます。

$ pip install retrying

他にもretryというものもあり、同様に簡単にリトライ処理ができるようです。

app.py
from chalice import Chalice                                                                                                                    
from datetime import datetime
from retrying import retry
import boto3
from botocore.exceptions import ClientError

app = Chalice(app_name='exponential-backoff')

def retryIfClientError(exception):
    print(datetime.now().strftime("%Y/%m/%d %H:%M:%S"))
    print('retrying...')
    # Falseを返すまで再試行をする
    return isinstance(exception, ClientError)

# retry_on_exception: 特定のException拾うため
# stop_max_attempt_number: 試行回数
# wait_exponential_multiplier: 乗数
@retry(retry_on_exception=retryIfClientError, stop_max_attempt_number=3, wait_exponential_multiplier=1000)
def retryS3Test():
    s3 = boto3.resource('s3')
    client = s3.meta.client
    response = client.get_object(Bucket='mybucket', Key='存在しないかもしれないファイル')

@app.route('/')
def index():
    retryS3Test()
requirements.txt
retrying==1.3.3

chaliceのプロジェクトをdeployしてEndpointを叩くと、CloudWatchLogに以下の様なログが出て再試行されてるのがわかるはずです。

スクリーンショット 2017-07-29 18.40.38.png

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?