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に以下の様なログが出て再試行されてるのがわかるはずです。