← все видео

AI Fraud Detection on AWS | Serverless Event-Driven Saga with Bedrock

lokeshmateti · 2026-07-13 · 34м 48с · 700 просмотров · YouTube ↗

Топики: durable-execution

🎧 Аудио

📝 Summary

model=deepseek-v4-flash · prompt=summary-v7 · 7 491→2 514 tokens · 2026-07-20 15:08:33

🎯 Главная суть

На AWS развернута event-driven платформа обработки заказов с AI-детекцией мошенничества через Amazon Bedrock. Архитектура реализует Saga-паттерн для распределенных транзакций: при успехе выполняются четыре шага (резервирование инвентаря, фрод-чек, оплата, подтверждение), при сбое любого шага — автоматические компенсационные действия (отмена резерва, пометка заказа как failed). После подтверждения заказа EventBridge разветвляет уведомления (SES) и индексацию (OpenSearch) через две независимые SQS-очереди с DLQ.


Архитектура: API Gateway → Lambda → Step Functions (Saga)

Пользователь отправляет POST-запрос на API Gateway, который триггерит order-processor Lambda. Эта Lambda:

Saga состоит из четырёх Lambda-шагов: ReserveInventory, FraudCheck, ProcessPayment, ConfirmOrder.
При успехе всех шагов статус заказа меняется на confirmed, и срабатывает ConfirmOrder Lambda, публикующая событие OrderConfirmed в EventBridge.


Saga-паттерн и компенсации

Если любой шаг завершается ошибкой, Saga автоматически выполняет компенсацию:

Компенсация гарантирует консистентность данных между распределёнными сервисами без использования распределённых транзакций БД.


AI-фрод-детекция через Bedrock

В шаге FraudCheck Lambda формирует промпт с деталями заказа (номер, customer ID, email, сумма, количество единиц товара и т.д.) и отправляет его в модель Bedrock (LLM).

Первоначальные критерии в промпте:

Модель возвращает fraudScore (от 0 до 1 по умолчанию) и riskLevel. Порог отбраковки — >= 0.7.


Тест 1: Happy path


Тест 2: Insufficient stock


Тест 3: AI-фрод-детекция (отбраковка)

Сначала использован промпт с «плоскими» критериями (каждый сигнал давал скор до 1.0, но общий скор мог не достичь 0.7 при нескольких сигналах).

Первый запуск: invalid-email, quantity=40, сумма $3960. Bedrock вернул fraudScore=0.5 — заказ прошёл успешно (ложное срабатывание).

Автор обновил промпт: каждому критерию назначен фиксированный вес (например, high order total → +0.3, suspicious email → +0.4). Если присутствует более одного высокорискового сигнала — итоговый скор должен быть >=0.8.

Второй запуск: те же параметры (invalid email, qty=40). Bedrock вернул fraudScore=1.2 с перечислением причин:

Заказ отклонён. Компенсация сработала: инвентарь не уменьшился (остался 57). Статус в DynamoDB — failed. Письмо не отправлено.


Тест 4: Payment failure с компенсацией

Автор внёс временное изменение в ProcessPayment Lambda — закомментировал основной код, чтобы она всегда падала с ошибкой.


ElastiCache: кэширование продуктов

При первом обращении к продукту — промах (miss) — чтение из DynamoDB и запись в Redis. Последующие запросы того же продукта обслуживаются из кэша (cache hit), что снижает нагрузку на БД.
Этот сценарий упомянут как scenario 5, но в демо не показан.


Terraform для OpenSearch и ElastiCache

Для экономии средств OpenSearch и ElastiCache развёрнуты через Terraform — их можно быстро создать и удалить. Остальные сервисы (Lambda, Step Functions, SQS, SES, API Gateway, DynamoDB) — serverless с оплатой только за использование, поэтому они созданы вручную.


Репозиторий и документация

В репозитории доступны:

📜 Transcript

en · 4 689 слов · 61 сегментов · clean

Показать текст транскрипта
Hello everyone, welcome back. In today's video, I'm going to walk you through a complete event-driven order processing platform that I have built on AWS. And what makes this special is that it includes AI-powered fraud detection using Amazon Bedrock. This is a real-world architecture that covers several important patterns, the saga pattern for distributed transactions, event-driven fanout using the event bridge, and SQS and AI integration inside a serverless workflow using Amazon Bedrock. Before we jump into the demo, let me quickly walk you through the architecture. So this is our architecture. So here, when a customer places an order, the request fits the API gateway, which triggers the order processor Lambda. This Lambda does three things. It validates the request. checks the elastic cache readies for cached product, cached product data to avoid unnecessary DynamoDB reads and writes the order as ending to DynamoDB. Then it kicks off the step functions that is saga. So if you see this one, so this complete block, it is a step functions and we have given name as order as saga as the step function name. So the saga has four main steps. One is reserve inventory, fraud check, this is using via bedrock and then process payment and confirm order. And once it is done, it comes out as succeeded. So, each step is a separate lambda. So, whatever we see all this reserve, fraud check, payment, confirm. So, everything is a separate lambda functions. So, the fraud check step is where AI comes in. It calls Amazon bedrock with the order details and gets back a fraud score. If the score is above 0.7, the order is rejected. If any step fails, Saga automatically compensates releasing reserved inventory and making the order as failed. So, this is the Saga pattern. It ensures data consistency across distributed services. without using database transactions. So, once order is confirmed, the confirmed order lambda publishes an order-conformed event to EventBridge which fans out two SQS queues simultaneously. One for email notifications via SES, simple email service and one for indexing the order in OpenSearch. Each queue also has a dead letter queue. If your message fails to process after three attempts, it goes to the real queue for investigation. So now let me show you this in action with four scenarios. So let me open the test scenarios. And before we proceed for the scenarios, so I have listed out what and all services that we are using in this particular project and other details I have mentioned in detail here. So, if you would like to try this project in this readme and the other docs will help. So, now let's get started with scenarios. So, first scenario that is I am going to place an order using the curl command. So, before I place an order, so I will show you the table details. Let me open the DynamoDB tables. So, if we see here, we have three tables here. So, one is product so we have two products product 001 product 002 and what are those products and their names and price and order details so what and all orders that we have placed so all the details we have here and its status and coming to the inventory so how many products are still available in stock and how many products are not available for example if i place one order this stock currently it is showing as 98 so this stock should reduce one count that means after that its value should be 97. so all this inventory it will maintain so now we will go back and test the first scenario okay so that we call it as happy path that means let's say if this is successful in all the stages okay then what and all what are the steps that we need to check so that we are going to see it now okay let's give a try so now i will open my terminal so i am using the curl command and if you see this is my api gateway and this is the api gateway domain and this is the stages and this is what i have applied and coming to other details so i gave my email id and the product 001 i gave and the other field details i gave and then quantity one i'm giving so let me hit enter okay so now it created it created order, order ID and its status is pending. And if you see the order ID, it is ending with 357. So now we will go to this one, step functions. Before that, so this is the API gateway, which I, which I said, and this is the number which we have triggered now. It is ending with 07A, 07A and orders, and I have placed a post. So, and if you see this one, and this will triggers. order processor lambda okay and this order processor lambda triggers the step functions okay so let me open the order server which is our step function name and let me go back and check what is the order we placed it is ending with 357 and if you see this is the one which we placed just now and timestamp we can see so if we go inside see this is showing all the details like what and all lambdas that it got executed successfully And if I see this one, it is successful altogether. So let me cross check the details. So order number what we have seen, it is ending with 357 and email ID. So all the details we can see. And coming to let's check the fraud check. So what it is showing for us. So if you see this one, so fraud score is 0, risk level low and the fraud check equal to 2. So that means the fraud check case it passed. So and then it proceeded with the process payment. And even this case, it is successful. So, yeah. So, in the saga step function side, all the scenarios are successfully executed. Okay. Let us check what are other things that we need to cross check. So, what we have cross checked now? We have cross checked the step functions latest execution state and all other states. Also, we see this score. It is score is less than 0.7. I think in our case, it is 0.0. Let me cross check that one. Now fraud score is just 0. So that is why it is passed now. Let me open the other checks that we can do. So this is done now. Let's cross check the DynamoDB order stable and check the status. I will go to DynamoDB. I will go to order stable. So let me open the order number. So that is ending with 357. This is the order number. And if you see this one. so it is confirmed status is confirmed so yeah this check also success now and uh inventory we will see so this inventory should be decremented by one so earlier when we have seen before executing this command it was showing 98 right so now let's go back and check okay this one okay now i just now refreshed this one so now if we see this status is 97 okay so yeah so even this is confirmed and the inventory table also updated by the corresponding lambda and now we should get a email to our inbox so let me cross check my inbox okay so for the specific order so order number ending with 357 and i have received a mail from ses okay so your order has been confirmed and this is the price okay so yeah this is also successfully done now let's cross check the cloud logs so we will check the email consumer logs and we should see email sent for this particular order okay now i will go to So now I will go to, let me go to log management. So first we will check email consumer. So we will check email consumer. So in the email consumer, we will open the latest one. Here we can see email sent for order ending with 357. So in this case, so we see that email sent for order also present. Now we will check. search consumer logs in CloudWatch logs. So let me open the CloudWatch logs. So we look for search consumer logs. Now we see indexed order. So order number is 357. So we can see like even this particular order information has been indexed in the open search. So now we can cross check this data in the open search. So in simple way, whenever we hit any, whenever there is any successful record and the count, the document count will increase by 1. Let me open the open search. So, now we will go to domains. So, if I click on indexes, see three order details has been indexed here, has been inserted here. And if I hit one more, I think this number will get increased to 4. So, this information we can data we can see in the dashboards okay for now let's check what are the fields it is data is getting inserted here okay these are all the tweets it is having in the open search okay so now so the first scenario that is happy path scenario like all the scenarios all the check boxes are successfully successfully done here now what we will do we will try insufficient stock okay if it is a insufficient stock for example if i placed an order For example, if the quantity for available stock is I think 97, if I place quantity of 1000, then it should create saying that there are no sufficient stocks. In this case, how state functions compensate the request, so that we will check now. So, before we check, let us cross check the inventory table stock value first. So, now we will go to inventory table. So, right now we have stock 97 okay now i will go to this one so i let me run quantity number as thousand or above 97 okay let me run the command so in the first scenario happy part scenario i gave quantity as one but now i will give let's say i will give thousand as quantity but whereas in our actual in in the database stock value we only have 97 in this scenario it should fail with message insufficient stocks. So, let me, let us try this one. So, it created an order with the status as pending and this order number is 3 e b. So, now we have executed this command. Now, what and all we have to verify, I will go to step functions. So, let me go here. So, this one ending with order number ending with 3 e b, what we have just executed and we can see the stages. So, reserve inventory, let us check the output here. So, what is the error? It says insufficient stock for product 001. So, once this is done, it is not even going to any other checks. It is not going to fraud check or process payment, nothing. It will directly come to the failure state, order failed. So, we can see order failed state, it will come directly. So, let me cross check as per this data. So, this we have explained. So, it did not even executed. Now, we will go to DynamoDB and check the status there. So, this particular order ending with 3EV, we will go to, we are in DynamoDB and go to orders and let me open the order what I created ending with 3EV and if you see the status, status is fail. Now, there should not be any emails also for this particular request. So, let me open my inbox. Generally, it comes in spam. Let me open. if you see last order that is happy path scenario ending with the 357 only we have and I did not receive any maker order number 3 e b okay so okay let me cross check email consumer okay there should not be any new entry for the email consumer I will go to cloud watch okay so I will go to log groups I'll go let's go to log management so email consumer they need to check email consumer let me refresh If you see the latest one is ending with order number 357. That means it is the previous order, not the current one. So, there is no entry even in the flower watch logs. So, this is clear that if there are, if there is no sufficient stock, it will straight away fail and it will make the DB entry also status as failed and subsequent tasks like even it will not trigger for the email as well. Now, let me check the fraud detection. which is a power one. And here, the expectation is inventory reserved a flag order as a fraudulent score greater than or equal to 0.7. If this is the case, then inventory will be released and order will be failed. So, before we run this scenario, let me cross check the inventory, inventory table and note the what is the stock value. So, let me go to the DynamoDB. And I will go to inventory table. Let me refresh. So, stock value is 97 only because the previous one also failed due to insufficient stocks. So, now we will go back and execute this command. So, before I execute this command, I would like to show you what and all the scenarios that AI will analyze and give the score. Let me go to the fraud check lambda. So, we will go to fraud check lambda. So, as I mentioned earlier, we are using a bedrock, through bedrock, we are using a model. I will just explain that one. So, this is the prompt we are giving. So, order number, all the details we are giving, customer ID, customer email, and all other details we are giving, and what and all we are asking, evaluate for. So, we are asking A to look all these scenarios. If you see this one fraud score 0.0 and other scenarios, for example, if you see this one, so based on all these conditions, it gives the fraud score. And if we come to model, so this is the LLM that we are using from the bedrock. So based on that, it will provide us the score. So now let us go back and check. So main scenarios, what scenarios? One is unusual high order total. If it is... greater than 500 dollars is suspicious if it is greater than 2000 is high risk and unusual large quantity per item if it is greater than 10 is suspicious greater than 50 is high risk and suspicious email domain like any random strings uh disposable email providers and the price anomalies so in this in this case in one of the uh case what i will do i will give some wrong email id and then i will see how a powered if not check happens and provides the results to us. Let us go back and give a try. So, let me cross check the scenarios. In this scenario, so what we are giving? So, email id, wrong domain we are giving. So, let me run this with some invalid email id. Also, this quantity I will give more quantity. Let me run that. So, I have given some invalid email id and the quantity is I gave 40. okay let me hit enter okay so uh what is the number ending with order number is eca okay now let me go here so okay so as per the above command okay these are all the like bulk quantity we gave 40 okay and then the email ad suspicious email ad we gave and the high total and the price anomaly flat by a so these are all uh being given in this curl command now we will verify the step functions okay let me open the step functions yeah refresh okay let me open the latest one let me refresh so what is the number pca okay let's check the project analysis so if you see the output so i gave invalid email id also the quantity is high okay quantity i gave 40. so it says units per item is suspicious also harder total of 3960 dollars is unusual but fraud score it gave only 0.5 so that is the reason it did not fail because in the i have given condition as if it is greater than or equal to 0.7 then it should fail uh so i think that is the reason it gave my success so to fix this issue uh so i i just now i have updated my prompt right so i gave a specific scores for individual items so i gave for high order total i gave a score 0.3 in the similar way i gave score for each item for example if it is email domain related then the score is you can see 0.4. So, if more than one high risk signal is present, then consider score must be greater than or equal to 0.8 dimension. If you see here, so we have high risks here. This is one high risk and this is one high risk. So, if any scenarios like if it is more than one high risk, then consider it is 0.8. That means it would be a fraudulent order, then just reject it. So, that is the expectation now. So, if you see this one, if it is greater than or equal to 0.7, then flagged as fraudulent and mention the score and the reasons. So, let me, I just now ran one command, I deployed it already and ran one command. Let me rerun it again. So, I am giving again an invalid email id, also the quantity I gave, 40. Let me run it. Let us pick up the order id from here and then proceed for step functions. I forgot to hit enter. I have your new order ID ending with 167. Let us go to execution of state functions. So, order number ending with 168. If you see this one 168 is failed now. Let me check this graph view. So, reserve inventory is fine, success. Let us check the fraud check what output it is giving now. So, now if we check, so error message it says for the order ending with 168 flag dash fraudulent core is 1.2. So, reasons, unusual high order total greater than 1000 is high risk and unusual quantity per item greater than 20 is high risk. Suspicious email domain, that is what we have mentioned, that is this user, this is another high risk and the price anomalies. So, based on all these things, so AI powered check has given a score of 1.2 and it got failed. So, once this is failed, it will not execute any other stages here let's say process payment or confirm order any other states it will not go directly it will come to the release inventory after fraud fail okay based on this error and then it will fail the order and then order failed so let's go back and check okay if the what and all other things that we can cross check right so this we have right now we have cross checked all this order like a failed order order failed or following same state so now fraud score also we have checked that is 1.2 and then inventory table now we will go to fraud 001 stock restore to the original value okay so the expectation is it should not update the stock meaning it should not decrement the inventory right so let me go to the inventory table items let me go to inventory table and refresh okay yeah this scenario because we have a successful scenario in between. So, when the Farrar check did not happen, 40 orders has been placed successfully. So, that is why it is 97 minus 40, that is 57. So, even in the second scenario also, it is still at 57 only. So, for checking, let me give a try again and see. So, the expectation is this 57 should not change. And in between, let me cross check the orders. If you see the 168 order, what we placed. This one 168 which reported or rejected by the AI powered check. So, in DB also it says the status has failed. Now, we will check the inventory status also. I will hit again. So, similar quantity same command. So, the expectation is inventory currently it is 57. It should not change. Now, the order number ending with 41D. Now, I will go to state function, step functions. So, let me refresh. So, 41d order number ending with, let me open this one. So, now also it is failed and the other states did not get executed. Now, we will go to inventory and cap check. So, if we see 57, it is still at 57 only. There is no change and coming to the orders, it should be failed state. So, 41d ending with, so it is in failed state. So, order also did not placed. And we can also check. there should not be any there should not be a mail for this particular order so for which order order number 41d okay so if you see this one this is the previous successful order okay and there is no mail for 41d so order number ending with eca eca is the previous order right this this order which was successful since the fraud check did not give the correct score okay so okay let me go back okay and let's check that scenario 4. In the scenario 4, so what happens if payment failure, payment failed? Let us check payment failure with the compensation. So, the expected results are inventory reserved, fraud check passes, but payment fails. In this case, so it should, inventory should get released and order should be failed. So, before proceeding, let us go back and check the stock value in the inventory table. Let me go to the DynamoDB and I will check the inventory, inventory table and refresh. So, stock value is for product 001, it is 57. So, let me go back and what we will do in the process payment lambda, we will make the change, this change we will make. So, we are forcefully making this to fail, payment to fail and then we will see how remaining states will compensate the scenario. So, let me. make this change first in this lambda. I will open the process payment lambda. So, these are all the lamb that we have. I will open the process payment lambda. In this, let me, just give me a minute. In this process payment lambda, so we will, let us comment this one. So, with this change, we are forcefully making the process payment to fail. So, let me deploy this change. the function code has been updated and deployed in another data. Accept. Let us verify and then proceed. So, changes are present. Let me go to the curl command. So, in this curl command, so we are giving the correct email id, valid email id and remaining details also correct and the quantity also I am just giving 1. So, the expectation is fraud check also should pass now, only it should fail in the process payment state. Let me hit enter. So, Harder number is 37A. Let me go to step functions. Let me refresh. So, 37A, harder number. So, reserve inventory is success. Broad check also success now. Let me check the output. It says score is 0. Risk level is low. And it is true. So, this is passed now. Now, coming to the process payment. So, process payment is failed now. for the particular order, release 7a order, it failed due to some exception. So, once the process payment is failed, it did not proceed for the conforming order or release inventory, all these scenarios. So, it came to release inventory after this scenario. So, and then it failed the order. So, if you see this one, inventory released true. So, let me cross check. So, what we have done, we have executed with the curl, we have executed this curl command with the required inputs. And so, this is success, even fraud check calls is success, process payment is caught some errors. And after that, it redirected it to release inventory after payment fail, fail and fail order, order fail. So, this is done as expected and verify compensation work. So, now what we have to check, we will go to inventory table and there should not be any decrement in the stock. So, let me go to the items, inventory. And this is the 57 what you have seen before. Let me refresh. So, there is no decrement happened in the inventory. That means there is no change in the inventory. So, that is expected. So, now, yeah. So, now, order table if you go for this particular order, order ending with the 37A, even the state status should be failed. Okay. So, let me go to the orders. So, 37A and its status is failed. Okay. So, yeah. So, since... Since we have tested this scenario, I will just revert this change back to this change, random dot random. So, let me go back to the process payment. So, I will revert the change and then deploy it. I successfully updated the function. So, with this, we have covered all the four scenarios and coming to the scenario 5. So, this is elastic cache. Cache hits versus misses. When the cache will hit and then when it will miss. So, the first product lookup. It hits the DB, and it will be a miss from the elastic cache and subsequent looks up, server from the Redis. So, this is the main use case of this one. So, I have deployed elastic cache also, but this scenario, so I have not tested here. So, you can give a try. So, before we close, this is the repository. So, all the lambdas, so I, created manually and updated updated code so we can also do it through the terraform but uh fundamentally i created it manually uh so yeah we can see all the lambda and its code has been uh lambda function code has been updated here so if you want to give a try you can try also so to brief so we i have added all the docs here architecture design and policies and other details my scenarios what we have tested and coming to the step functions so this is the all the states what we have like reserve inventory and project all the states process payment so the step function related JSON file is present here also for the open search and elastic cache for these two I'm provisioning using the terraform okay and remaining all the main reason of using the terraform for these two is these will be these two services will be chargeable and others other lambda functions and step functions sq sqs and scs it is all like uh only whenever whenever i use only i need to pay so remaining even though it is running i don't have to pay for those services so that is the reason so for in the terraform only for the open search and elastic cache i have used terraform to provision and remove the instances when i am not testing this that's all i would like to share for today thank you

⚙️ Pipeline jobs

StageStatusAtt.UpdatedError
download done 1/3 2026-07-20 15:07:47
transcribe done 1/3 2026-07-20 15:08:05
summarize done 1/3 2026-07-20 15:08:33
embed done 1/3 2026-07-20 15:08:35

📄 Описание YouTube

Показать
I built a fully serverless, event-driven order processing platform on AWS — and dropped an AI fraud detection step right into the middle of the Saga, using Amazon Bedrock. In this video I walk through the architecture and then run four live scenarios, including one where the AI catches a fraudulent order mid-transaction and the Saga compensates automatically.

⭐ Source code: https://github.com/lokesh-mateti/event-driven-order-processing-aws

The stack: API Gateway → Lambda → Step Functions (Saga) → EventBridge → SQS (with DLQs) → SES + OpenSearch, with DynamoDB for state, ElastiCache Redis on the read path, Amazon Bedrock for AI fraud scoring, and Terraform for infrastructure.

━━━━━━━━━━━━━━━━━━━━

WHAT YOU'LL LEARN

- The Saga pattern — how to keep data consistent across distributed services without a database transaction
- Compensating transactions — releasing reserved inventory when a downstream step fails
- Event-driven fan-out — one EventBridge event triggering two independent consumers in parallel
- Dead Letter Queues — what actually happens when a consumer fails
- AI in the transaction path — calling Amazon Bedrock from a Lambda inside a Step Functions workflow
- Why the API returns before the Saga finishes, and why that's the point

━━━━━━━━━━━━━━━━━━━━

THE FOUR SCENARIOS

1. Happy path — order confirmed, email sent via SES, order indexed in OpenSearch
2. Insufficient stock — Saga fails at ReserveInventory and never reaches fraud check or payment. Nothing to compensate
3. AI fraud detection — Bedrock scores the order 0.75 and blocks it. Inventory was already reserved, so the Saga releases it and marks the order FAILED
4. Payment failure — fraud check passes, payment fails, inventory gets released. Same compensation, different trigger


AWS SERVICES USED

Amazon API Gateway · AWS Lambda · AWS Step Functions · Amazon DynamoDB · Amazon EventBridge · Amazon SQS · Amazon SES · Amazon OpenSearch Service · Amazon ElastiCache (Redis) · Amazon Bedrock (Nova Micro) · AWS IAM · Terraform

Everything except OpenSearch and ElastiCache costs nothing at idle — the whole thing is pay-per-use. A single AI fraud check runs about $0.001.

━━━━━━━━━━━━━━━━━━━━

Full setup instructions, IAM policies, and test scenarios are in the repo README. If you build this yourself and get stuck, drop a comment.

#AWS #Serverless #EventDriven #Bedrock #SagaPattern