Preventing Duplicate Executions in Step Function
Sometime we might have a hard requirement to prevent executing this state machine twice with the same input.
We can use the default feature of start_execution API for Step Fucntion for preventing dupe executions.
Start Execution Request Syntax
---------------------------------------------------
{
"input": "string",
"name": "string",
"stateMachineArn": "string"
}
Cases:
-------------
Invoke Step Functions with a name 'A': the execution will be successfully invoked and is assigned that name.
Invoke Step Functions with the same name 'A': If the execution is running with same name, the Step Functions API will return the same response as the original request.
Invoke Step Functions with the same name 'A': If the execution with name 'A' has completed (failed/successful) or teh Step Function is running with some other name , the Step Functions API returns an error --
Execution Already Exists.
Configure name:
-------------------------
1)In Order Processing Workflow , to avoid processing same order twice , we can use order id as name
2)Apply hashing (e.g. md5) on your json payload and use the hash value as the execution name.
V.V.I.
--------
Execution names can be used after 90 days , so there can be a possibility of reprocessing of same input after 90 days..
In that case , we need a custom solution using a datastore to keep track of execution.
Step 1:
--------------
Create an SNS Topic & create an email subscriber
Step 2:
--------------
Create a Step Function to publish the message in the SNS Topic after some wait time
Step 3:
--------------
Lambda Code:
----------------------------
import json
import boto3
import hashlib
client = boto3.client('stepfunctions')
def lambda_handler(event, context):
# TODO implement
print(event)
country_name=json.loads(event['body'])['country']
encoded_country_name = hashlib.md5(country_name.encode()).hexdigest()
input_json=json.dumps({"body":'I love my {}'.format(country_name)})
try:
response = client.start_execution(
stateMachineArn='',
name=encoded_country_name,
input=input_json
)
print(response)
send_back={"execution_arn":response['executionArn']}
return {
'body': send_back
}
except client.exceptions.ExecutionAlreadyExists as e:
return 'Already executed'
Step 4:
----------------------
Create API using API Gateway to trigger the Lambda Funciton
Step Function Json:
-----------------------------------------
{
"Comment": "A description of my state machine",
"StartAt": "Wait",
"States": {
"Wait": {
"Type": "Wait",
"Seconds": 30,
"Next": "SNS Publish"
},
"SNS Publish": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish",
"Parameters": {
"Message.$": "$.body",
"TopicArn": "{SNS ARN}"
},
"End": true
}
}
}
Prerequisite:
------------------------
Creating a POST Api | AWS API Gateway Passing Data to AWS Lambda
https://youtu.be/vgl9q5Ox5LE
To know more about the start_execution API , you can refer this link--
https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html
Boto3 documentation reference--
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions.htm #SFN.Client.start_execution
Learn AWS Step Fucniton from Scratch:
https://youtube.com/playlist?list=PLjfRmoYoxpNoahLvGnz_vJnOZ2FBQhaVu
Check this playlist for more AWS Projects in Big Data domain:
https://youtube.com/playlist?list=PLjfRmoYoxpNopPjdACgS5XTfdjyBcuGku
????????
YOU JUST NEED TO DO
3 THINGS to support my channel
LIKE
SHARE
&
SUBSCRIBE
TO MY YOUTUBE CHANNEL
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Preventing Duplicate Executions in Step Function», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.