Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

Preventing Duplicate Executions in Step Function

Автор: Knowledge Amplifier

Загружено: 2022-07-02

Просмотров: 2056

Описание:

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
   • Creating a POST Api | AWS API Gateway Pass...  

To know more about the start_execution API , you can refer this link--
https://docs.aws.amazon.com/step-func...

Boto3 documentation reference--
https://boto3.amazonaws.com/v1/docume...

Learn AWS Step Fucniton from Scratch:
   • AWS Step Functions Simplified  

Check this playlist for more AWS Projects in Big Data domain:
   • Demystifying Data Engineering with Cloud C...  

🙏🙏🙏🙏🙏🙏🙏🙏
YOU JUST NEED TO DO
3 THINGS to support my channel
LIKE
SHARE
&
SUBSCRIBE
TO MY YOUTUBE CHANNEL

Preventing Duplicate Executions in Step Function

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Recursion Pattern in AWS Step Function to process long-running task using AWS Lambda

Recursion Pattern in AWS Step Function to process long-running task using AWS Lambda

Вся правда о Steam Machine и Half-Life 3

Вся правда о Steam Machine и Half-Life 3

SCHOOLBOY VS ДЕВОН ЛАРРАТТ АРМРЕСТЛИНГ 2025

SCHOOLBOY VS ДЕВОН ЛАРРАТТ АРМРЕСТЛИНГ 2025

Декораторы Python — наглядное объяснение

Декораторы Python — наглядное объяснение

Самые важные паттерны в программировании

Самые важные паттерны в программировании

Арестович: Почему Трамп дает еще один шанс Зеленскому? Дневник войны.

Арестович: Почему Трамп дает еще один шанс Зеленскому? Дневник войны.

Adding manual approval step to the AWS Step Function workflow

Adding manual approval step to the AWS Step Function workflow

КАК НЕЛЬЗЯ ХРАНИТЬ ПАРОЛИ (и как нужно) за 11 минут

КАК НЕЛЬЗЯ ХРАНИТЬ ПАРОЛИ (и как нужно) за 11 минут

Getting started with AWS Step Functions with AWS Lambda & Athena

Getting started with AWS Step Functions with AWS Lambda & Athena

Бесконечный программный кризис – Джейк Нейшнс, Netflix

Бесконечный программный кризис – Джейк Нейшнс, Netflix

Градиентный спуск, как обучаются нейросети | Глава 2, Глубинное обучение

Градиентный спуск, как обучаются нейросети | Глава 2, Глубинное обучение

Protecting Sensitive Personal Data With Aggregation Policies In Snowflake | GDPR Regulations

Protecting Sensitive Personal Data With Aggregation Policies In Snowflake | GDPR Regulations

Самая сложная модель из тех, что мы реально понимаем

Самая сложная модель из тех, что мы реально понимаем

Что такое IP-адресация? Как работает IPv4 | IPv4 против IPv6 | 5 типов IP-классов | Публичный и ч...

Что такое IP-адресация? Как работает IPv4 | IPv4 против IPv6 | 5 типов IP-классов | Публичный и ч...

КАК УСТРОЕН TCP/IP?

КАК УСТРОЕН TCP/IP?

Как производятся микрочипы? 🖥️🛠️ Этапы производства процессоров

Как производятся микрочипы? 🖥️🛠️ Этапы производства процессоров

Краткое описание Agile Product Ownership

Краткое описание Agile Product Ownership

Почему Азовское море — самое опасное в мире

Почему Азовское море — самое опасное в мире

Шоу Путина: Ежегодная лапша на уши россиянам

Шоу Путина: Ежегодная лапша на уши россиянам

Шаблон повторных попыток: секрет отказоустойчивого кода на Python

Шаблон повторных попыток: секрет отказоустойчивого кода на Python

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: [email protected]