https://www.youtube.com/watch?v=YPbGW3Fnmbc
Spring Sagas
Use Case:
when an user places an order, order will be fulfilled if the product's price is within
the user's credit limit/balance. Otherwise it will not be fulfilled.
In the above pic, both the applications are pointing to the single database as the system is monolithic
and can be considered as a single transaction.
In case there's some issue with the Process Payment entire data will be rolled back. Not a single
data is inserted to db that's how transaction handled at monolithic.
Microservices generally follow database per service pattern. As we can see in the below images,
2 different databases are used. For monolithic the approach should be the same as monolithic.
1. It's not a good approach to fire n number of HTTP requests.
Eveytime a new service is added, HTTP request needs to be fired.
2. It will impact on the revenue is there's a application down time.
To overcome this issue, microservices provided a pattern called saga pattern.
We can implement saga pattern using two approaches:
1. Choreography
2. Orchestration
We can use Choreography pattern with the help of event sourcing so there will be no HTTP req call.
Following pic can be used to understand how transaction is done with the help of kafka topics
and there are no HTTP event calls:
curl --location --request POST 'http://localhost:8081/order/create' \
--header 'Content-Type: application/json' \
--data-raw '{
"userId": 103,
"productId": 33,
"amount": 4000
}'
{"eventId":"b0e47448-eeb8-4cf4-bd29-b3a4315fc592","date":"2021-09-03T17:26:46.777+00:00","orderRequestDto":{"userId":103,"productId":33,"amount":4000,"orderId":1},"orderStatus":"ORDER_CREATED"}
{"eventId":"c48c5593-9f81-4ab4-9de8-b9fca2d2bef2","date":"2021-09-03T17:26:51.989+00:00","paymentRequestDto":{"orderId":1,"userId":103,"amount":4000},"paymentStatus":"PAYMENT_COMPLETED"}
curl --location --request POST 'http://localhost:8081/orders' \
--header 'Content-Type: application/json' \
--data-raw '{
"userId": 103,
"productId": 12,
"amount": 800
}'
{"eventId":"fecacc77-017d-49cd-bdfa-58e47170da49","date":"2021-09-03T17:28:23.126+00:00","orderRequestDto":{"userId":103,"productId":12,"amount":800,"orderId":2},"orderStatus":"ORDER_CANCELLED"}
{"eventId":"46378bbc-5d15-4436-bed1-c6f3ddb1dc31","date":"2021-09-03T17:28:15.940+00:00","paymentRequestDto":{"orderId":2,"userId":103,"amount":800},"paymentStatus":"PAYMENT_FAILED"}
curl --location --request GET 'http://localhost:8081/orders' \
--header 'Content-Type: application/json' \
--data-raw ''
[
{
"id": 1,
"userId": 103,
"productId": 33,
"price": 4000,
"orderStatus": "ORDER_COMPLETED",
"paymentStatus": "PAYMENT_COMPLETED"
},
{
"id": 2,
"userId": 103,
"productId": 12,
"price": 800,
"orderStatus": "ORDER_CANCELLED",
"paymentStatus": "PAYMENT_FAILED"
}
]