Ravindra BagaleCourses & study guides English Track your progress

Serverless वर Distributed Transactions साठी Saga Pattern

दोन दुकाने एक ऑर्डर शेअर करतात: inventory आणि payment. Payment झाले पण inventory fail — charge undo करावा लागतो. हा undo नृत्य = saga. Serverless वर सहसा Step Functions.

या chapter मध्ये तुम्ही काय शिकाल

  • Saga vs 2PC
  • Happy + compensate
  • Orch vs choreo saga
  • Idempotent compensate
  • Link projects

1. रोजचे उदाहरण: दोन counters वर trip booking

Fatima (Casablanca) train (MAD 420) नंतर hotel. Hotel full → train cancel = compensation. Global lock नाही. Payment Lambda + stock Lambda तसेच.

order workflow project मध्ये steps; DynamoDB transactions मध्ये atomic multi-item. Cross-service = saga.

2. Saga का?

हे का लागतं?

Cross-service ACID नाही. Locks = Lambda वेळ/पैसे. Saga = local commit + compensate.

हे काय आहे?

Saga = local tx + compensate. Orchestration = SFN. Choreography = events.

3. Vertical diagram

Start -> Reserve -> Charge -> Ship -> EndCharge नंतर fail: RefundRelease
Compensate idempotent
Step Functions state machine 1 ReserveStock (Lambda) 2 ChargeCard (Lambda) 3 CreateShipment (Lambda) Success - notify SNS Catch: Refund (compensate 2) Then: ReleaseStock (compensate 1) Compensations run reverse order
Orchestration saga - forward ani reverse compensate.

4. Orch vs choreo saga

StyleProsCons
SFNHistory, timeout, catchCentral def
EventsLooseFlow unclear; loops
HybridMoney SFN; notify eventsdon models

Ravindra Bagale's Tip

Money/inventory = SFN. Marketing email = events.

5. How: payment+stock saga

कसं करायचं (step by step)

  1. AWS names nako - reserve/charge/ship.
  2. pratyek undo.
  3. orderId+step keys.
  4. SFN Catch chain.
  5. Completed fakt shevati.
  6. Failed + compensate alarms.

6. Commands + meaning

State machines yadi

aws stepfunctions list-state-machines --region ap-south-1 \
  --query 'stateMachines[].{N:name,A:stateMachineArn}' --output table

अर्थ: Mumbai madhye saga machine ahe ka te paha.

Failed execution

aws stepfunctions get-execution-history --region ap-south-1 \
  --execution-arn "$EXEC_ARN" --reverse-order --max-items 20 \
  --query 'events[?type==`TaskFailed` || type==`ExecutionFailed`]'

अर्थ: kuthla Task fail + error - compensate debug ithun.

Execution start

aws stepfunctions start-execution --region ap-south-1 \
  --state-machine-arn "$SM_ARN" \
  --name "ord-7841-$(date +%s)" \
  --input '{"orderId":"ord-7841","amountINR":2499,"sku":"MOMO-12"}'

अर्थ: Name unique; same name = juni execution.

Stop execution

aws stepfunctions stop-execution --region ap-south-1 \
  --execution-arn "$EXEC_ARN" --error "ManualStop" --cause "lab cleanup" 

अर्थ: Lab madhye loop stop; prod = alarm + runbook.

7. Compensation rules

  • Success chya reverse kram.
  • Compensate idempotent.
  • Compensate fail then human queue.
  • n zhalelya step cha undo nako.
  • orderId correlation.
  • Same currency refund.

8. kadhi saga nako

SmellBetterka
Single tableTransactWriteek request ACID
ek LambdaIn-processBoundary nahi
Read fan-outSNS/SQSUndo nahi

9. Industries

  • Fintech Lagos.
  • Ecommerce Pune.
  • Travel Sofia.
  • Healthcare SG.
  • Logistics Amman.

10. Lab: paper then SFN

11. Lab - sketch nantar state machine

Org block नसेल तर ap-south-1 (Mumbai). आधी budget alert.

कसं करायचं (step by step)

  1. Paper: 999 INR course - 3+3 steps.
  2. Order-workflow SM ughada.
  3. Test execution + Graph.
  4. Fail path + history.
  5. tumchya compensations liha.

Cleanup (billing थांबवा)

  1. Loops thambava.
  2. Lab SM delete.

12. एकाच pattern — वेगवेगळ्या industries

  • Fintech (Aisha, Lagos): payment webhooks → SQS → Lambda.
  • Ecommerce (Rohan, Pune): checkout API; inventory SNS fan-out.
  • Healthcare (Mei, Singapore): SNS SMS; PHI + fine-grained IAM.
  • EdTech (Diego, São Paulo): EventBridge nightly cleanup.
  • Logistics (Fatima, Casablanca): EventBridge + saga.
  • Media (Kenji, Osaka): S3 → Lambda thumbs + fan-out.
  • SaaS (Priya, Bengaluru): Cognito + per-tenant partition.
  • Gov (Omar, Amman): strangler fig per form route.

13. Troubleshooting checklist

  1. Region confirm करा.
  2. CloudWatch Logs + request id.
  3. Execution role permissions.
  4. DLQ + oldest message age.
  5. curl -v + CORS.
  6. SFN event history.
  7. Linked chapter पुन्हा वाचा.
  8. Cost: concurrency/retries.

14. सामान्य errors आणि fixes

प्रत्येक row = खरी चूक. Panic करण्याआधी fix वाचा.

Error / लक्षणFix
Task timeoutTimeout/VPC tapasa.
Double refundIdempotency + ledger.
Wrong compensateCatch scope.
Name existsUnique name.
Event loopVersion / SFN.
Ship after refundStatus gate.
Lost orderorderId in alarm.
Currency mixSame currency.
Payload bigS3 pointer.

15. FAQ

प्र. Saga=2PC?

nahi - local+undo.

प्र. ek table?

TransactWrite.

प्र. Express?

Short high-volume.

प्र. Async compensate?

Status track.

प्र. DDB tx?

Step aat; saga baher.

प्र. Project?

order-workflow.

16. Interview Q&A (Beginner / Mid / Senior + MNC)

प्र. Beginner saga

Local tx + compensate.

प्र. Compensate

Undo.

प्र. Mid orch

SFN vs events.

प्र. Idempotent refund

One credit.

प्र. Senior compensate fail

Human + no infinite.

प्र. MNC audit

History+ledger.

17. Tips — English, मराठी आणि हिंदी

Ravindra Bagale's Tip (EN)

Two counters, one trip: if hotel fails, cancel the train. That cancel is the saga.

Ravindra Bagale's Tip (MR)

don counters: hotel fail then train cancel = saga.

Tip (HI)

दो काउंटर, एक यात्रा: होटल फेल तो ट्रेन cancel — यही saga।

घरी करून बघा

  1. 3+3 steps liha.
  2. SFN vs SNS mark.

थोडक्यात सांगायचं तर

  1. गोष्टी पासून सुरू, मग services.
  2. Existing chapters link — labs copy नको.
  3. Failure साठी design.
  4. Measure → मग पैसे.

18. Architecture decision checklist

  1. User journey 5 bullets, no AWS names.
  2. Sync vs async mark.
  3. Failure mode.
  4. Idempotency key.
  5. Data from access patterns.
  6. Cost 1x and 10x.
  7. Quotas ap-south-1.
  8. Auth decision.
  9. On-call + alarm.
  10. Deep chapter link.
  11. मग console/IaC.

19. Copy-paste quick commands

# Region and identity
aws configure get region
aws sts get-caller-identity

# Lambda landscape
aws lambda list-functions --region ap-south-1 --max-items 20 \
  --query 'Functions[].{N:FunctionName,R:Runtime,T:Timeout,M:MemorySize}' --output table
aws lambda get-account-settings --region ap-south-1

# API Gateway (HTTP APIs)
aws apigatewayv2 get-apis --region ap-south-1 --query 'Items[].{N:Name,Id:ApiId,Ep:ProtocolType}' --output table

# Queues and topics
aws sqs list-queues --region ap-south-1
aws sns list-topics --region ap-south-1 --query 'Topics[].TopicArn'

# Event buses and state machines
aws events list-event-buses --region ap-south-1
aws stepfunctions list-state-machines --region ap-south-1 --query 'stateMachines[].name'

# DynamoDB tables (names only)
aws dynamodb list-tables --region ap-south-1

Sandbox + read-only IAM.

20. अजून industry आणि stack stories

  • Fintech Lagos: webhook → SQS → idempotent ledger.
  • Ecommerce Pune: throttle + fan-out.
  • Healthcare SG: SNS + PHI IAM.
  • EdTech: EventBridge cleanup.
  • Logistics: bus + saga.
  • Media: avoid recursive S3.
  • SaaS: tenant partition.
  • Gov: strangler peel.
  • Startup: Function URL → HTTP API.
  • Retail: FIFO vs Standard.
  • Python: thin handlers.
  • Node: async/await.
  • Java: SnapStart.
  • .NET: package size.
  • Go: static binary.
  • PHP: hybrid.

21. Glossary

Termअर्थ
Cold startपहिल्या invoke ची init
Idempotencyदोनदा = तोच effect
DLQFail झालेले messages
ChoreographyEvents; conductor नाही
OrchestrationSFN central
Fan-outएक → अनेक
Fan-inअनेक → join
Strangler figMonolith peel
SagaSteps + compensate
Provisioned concurrencyWarm N; pay

22. Practice: मोठ्याने explain

  1. 60s: saga pattern गोष्ट.
  2. 60s: sync vs async checkout.
  3. 60s: Lambda नको कधी.
  4. 60s: DLQ + idempotency.
  5. Record ×2.

23. Safe lab hygiene

  • Tag owner+expiry.
  • Budget alarm आधी.
  • Read-only first.
  • Cleanup.
  • No secrets in env/screenshots.
  • No provisioned on hello.

25. Myths

Mythखरं
Servers नाहीतServers आहेत; manage नको
नेहमी स्वस्तSteady वर EC2
No OpsIAM/data/alarms
एक LambdaBounded contexts
Queues optionalLoad leveler

26. Serverless error budget

Checkout error budget 0.1% असेल तर aggressive retries email duplicates देऊन budget जाळू शकतात. Money SLO ≠ notify SLO.

  1. दोन SLOs.
  2. Money retries bounded.
  3. Notify best-effort.
  4. Money page; notify ticket.

27. Regional notes (ap-south-1)

  • Labs Mumbai.
  • Feature availability.
  • Data residency.
  • Latency India.

28. Naming conventions

# Suggested prefixes
# Lambda:  pay-intake-prod, pay-worker-prod
# SQS:     pay-orders.fifo / pay-orders-dlq
# SNS:     pay-order-events
# EB bus:  pay.domain
# SFN:     pay-refund-saga
# DDB:     pay-orders-prod

env + domain नावात ठेवा. CloudWatch grep सोपा.

29. Pre-mortems

  1. Double charge headline.
  2. DLQ drain plan.
  3. Cognito outage mode.
  4. Runbook.

30. Currency / locale

Currencies आणि names rotate करा — global mental model.

31. Diego course (BRL)

  1. BRL 189.
  2. Reserve OK.
  3. Charge fail.
  4. Release; no welcome.
  5. No orphan seat.

32. Anti-patterns

  • Sleeps nako - SFN wait.
  • Compensate != forward.
  • Least privilege refund.
  • orderId in logs.

33. Metrics

  • ExecutionsFailed.
  • Compensate Errors.
  • RefundLatencyMs.
  • Human DLQ.

उजळणी, मुलाखत आणि तुलना cards

हा lesson काही मिनिटांत revise करा. Cards phone वर save करा किंवा PNG download करा. प्रत्येक card वरचा QR हा lesson उघडतो.

उजळणी card: Saga for distributed txns. Halfway fail. Saga + compensations. Forward → Catch → timeout. Sketch first.
उजळणी card: Saga for distributed txns · PNG download करा · Card page उघडा
उजळणी card: Compensation must be idempotent. Double refund. Idempotent undo. sagaId+step condition. Idempotency drill.
उजळणी card: Compensation must be idempotent · PNG download करा · Card page उघडा
तुलना: Orchestrated saga vs Choreography saga. Orchestrated saga: SFN conducts. Choreography saga: Events advance.
तुलना: Orchestrated saga vs Choreography saga · PNG download करा · Card page उघडा
तुलना: Two-phase commit vs Saga + compensate. Two-phase commit: Locks. Saga + compensate: Undo later.
तुलना: Two-phase commit vs Saga + compensate · PNG download करा · Card page उघडा
मुलाखत card: Why not 2PC. 2PC freeze. Saga over 2PC. Two reasons.
मुलाखत card: Why not 2PC · PNG download करा · Card page उघडा
मुलाखत card: SFN for orchestrated saga. Hand-rolled mess. SFN owns flow. ASL sketch.
मुलाखत card: SFN for orchestrated saga · PNG download करा · Card page उघडा
मुलाखत card: Choreography saga. Event spaghetti. Owned events. When which.
मुलाखत card: Choreography saga · PNG download करा · Card page उघडा
मुलाखत card: Timeouts on waits. Forever wait. Timeout + undo. Callback miss.
मुलाखत card: Timeouts on waits · PNG download करा · Card page उघडा

अजून cards: Ravi Sir's Cards.

सराव Tasks

या scenario बद्दल

Maple Leaf Books हा टोरांटो मधला पुस्तक विक्री व्यवसाय आहे. Emily Tremblay त्यांचं IT व cloud काम पाहतात. त्यांचे पैसे CAD मध्ये मोजले जातात आणि AWS resources ca-central-1 Region मध्ये चालतात. खालच्या tasks मध्ये तुम्ही या lesson मध्ये शिकलेलं वापरून त्यांची खरी कामं करता. सगळी नावं, account IDs, IP addresses व numbers सरावासाठी काल्पनिक आहेत.

0 / 16

सोपं Saga

का: Idea.

काय करायचं: Saga तर 1.

कसं करायचं:
  1. Task मधले numbers लिहून घ्या.
  2. कागदावर step by step काढा.
  3. Box मध्ये फक्त final उत्तर लिहा.
  4. Check answer दाबा.

सोपं Comp

का: Undo.

काय करायचं: Undo तर 1.

कसं करायचं:
  1. Task मधले numbers लिहून घ्या.
  2. कागदावर step by step काढा.
  3. Box मध्ये फक्त final उत्तर लिहा.
  4. Check answer दाबा.

सोपं SFN

का: Fit.

काय करायचं: SFN saga तर 1.

कसं करायचं:
  1. Task मधले numbers लिहून घ्या.
  2. कागदावर step by step काढा.
  3. Box मध्ये फक्त final उत्तर लिहा.
  4. Check answer दाबा.

सोपं 2PC

का: Anti.

काय करायचं: Avoid 2PC तर 1.

कसं करायचं:
  1. Task मधले numbers लिहून घ्या.
  2. कागदावर step by step काढा.
  3. Box मध्ये फक्त final उत्तर लिहा.
  4. Check answer दाबा.

सोपं List-sfn

का: CLI.

काय करायचं: list.

कसं करायचं:
  1. Task वाचा आणि ते कोणत्या AWS service बद्दल आहे ते ठरवा.
  2. aws लिहा, मग service चं नाव, मग operation (action शब्द).
  3. प्रत्येक आवश्यक flag (--name) व त्यापुढे task मधली value लिहा.
  4. Flags कोणत्याही क्रमाने चालतात. Check answer दाबा.

सोपं Parts

का: Map.

काय करायचं: forward/undo.

कसं करायचं:
  1. Task मधल्या top-level keys पासून सुरू करा.
  2. Child keys 2 spaces ने indent करा (tabs नकोत).
  3. प्रत्येक property मध्ये task मधली value भरा.
  4. Check answer दाबा. Keys चा क्रम महत्त्वाचा नाही.

सोपं Money

का: Fit.

काय करायचं: Money saga तर 1.

कसं करायचं:
  1. Task मधले numbers लिहून घ्या.
  2. कागदावर step by step काढा.
  3. Box मध्ये फक्त final उत्तर लिहा.
  4. Check answer दाबा.

मध्यम Choreo

का: Style.

काय करायचं: Events तर 1.

कसं करायचं:
  1. Task मधले numbers लिहून घ्या.
  2. कागदावर step by step काढा.
  3. Box मध्ये फक्त final उत्तर लिहा.
  4. Check answer दाबा.

मध्यम Idem

का: Safe.

काय करायचं: Idempotent तर 1.

कसं करायचं:
  1. Task मधले numbers लिहून घ्या.
  2. कागदावर step by step काढा.
  3. Box मध्ये फक्त final उत्तर लिहा.
  4. Check answer दाबा.

मध्यम Order

का: Flow.

काय करायचं: Reserve charge ship तर 1.

कसं करायचं:
  1. Task मधले numbers लिहून घ्या.
  2. कागदावर step by step काढा.
  3. Box मध्ये फक्त final उत्तर लिहा.
  4. Check answer दाबा.

मध्यम Catch

का: SFN.

काय करायचं: Catch compensate तर 1.

कसं करायचं:
  1. Task मधले numbers लिहून घ्या.
  2. कागदावर step by step काढा.
  3. Box मध्ये फक्त final उत्तर लिहा.
  4. Check answer दाबा.

मध्यम Styles

का: Map.

काय करायचं: orchestrated/choreographed.

कसं करायचं:
  1. Task मधल्या top-level keys पासून सुरू करा.
  2. Child keys 2 spaces ने indent करा (tabs नकोत).
  3. प्रत्येक property मध्ये task मधली value भरा.
  4. Check answer दाबा. Keys चा क्रम महत्त्वाचा नाही.

अवघड State

का: Ops.

काय करायचं: Persist state तर 1.

कसं करायचं:
  1. Task मधले numbers लिहून घ्या.
  2. कागदावर step by step काढा.
  3. Box मध्ये फक्त final उत्तर लिहा.
  4. Check answer दाबा.

अवघड Timeout

का: Bound.

काय करायचं: Timeouts तर 1.

कसं करायचं:
  1. Task मधले numbers लिहून घ्या.
  2. कागदावर step by step काढा.
  3. Box मध्ये फक्त final उत्तर लिहा.
  4. Check answer दाबा.

अवघड Partial

का: Reality.

काय करायचं: Partial → comps तर 1.

कसं करायचं:
  1. Task मधले numbers लिहून घ्या.
  2. कागदावर step by step काढा.
  3. Box मध्ये फक्त final उत्तर लिहा.
  4. Check answer दाबा.

अवघड Lab

का: Hygiene.

काय करायचं: Delete lab तर 1.

कसं करायचं:
  1. Task मधले numbers लिहून घ्या.
  2. कागदावर step by step काढा.
  3. Box मध्ये फक्त final उत्तर लिहा.
  4. Check answer दाबा.