Managing Distributed Transactions

1. Understanding ACID vs BASE Properties

PropertyACIDBASE
ConsistencyStrongEventual
AvailabilityMay sacrificePrioritized
UseSingle-DB txDistributed services
ExamplesPostgres, MySQL InnoDBDynamoDB, Cassandra

2. Understanding Two-Phase Commit

PhaseAction
1. PrepareCoordinator asks all RMs to vote
2. Commit/AbortIf unanimous yes → commit; else abort
IssuesBlocking, coordinator SPOF, poor scale
VerdictAvoid in microservices; use sagas

3. Implementing Saga Pattern

ConceptDetail
SagaSequence of local transactions across services
Forward stepPerforms business action
CompensationSemantic undo of completed step
Failure recoveryRun compensations in reverse
Order ─► Pay ─► Reserve ─► Ship   (forward)
       ◄─Refund◄─Release ◄─Cancel  (compensation)
        

4. Using Compensating Transactions

ForwardCompensation
Charge paymentRefund
Reserve inventoryRelease reservation
Send confirmation emailSend cancellation email
Allocate shipping labelVoid label
Warning: Compensations are semantic, not technical rollbacks — design with business intent.

5. Implementing Saga Orchestration

AspectDetail
Central orchestratorSends commands, tracks state machine
ProsEasy to reason; centralized monitoring
ConsOrchestrator becomes complex
ToolsCamunda, Temporal, Step Functions, Axon

6. Implementing Saga Choreography

AspectDetail
Event-drivenEach service reacts to prior service's event
ProsNo central point; loose coupling
ConsHard to trace; cyclic dependencies risk
Best forSimple flows, ≤ 3 services

7. Handling Transaction Isolation

IssueMitigation
Lost updatesOptimistic locking + version
Dirty reads (saga in-flight)Mark records "pending"; filter from queries
Fuzzy readsIdempotent writes; semantic locks
PatternSaga isolation: pivot transaction, semantic lock

8. Managing Transaction Timeouts

ScopeDefault
DB transaction1–30s
Saga stepPer-step deadline
Whole sagaMinutes–hours; trigger compensations on expiry
ToolingTemporal: built-in workflow timers

9. Implementing Idempotency

TechniqueDetail
Idempotency keyPer request unique ID
Natural IDUse business key (orderId)
Conditional updateWHERE version = ?
Dedup tableInsert key with unique constraint

10. Using Event-Driven Consistency

ElementDetail
Domain eventFact published on success
SubscribersUpdate local projections
OutboxAtomic write + publish
Idempotent consumerSafe replay

11. Handling Partial Failures

ScenarioAction
Step succeeds, ack lostIdempotent retry safe
Step fails mid-wayCompensate completed steps
Compensation failsRetry; alert on persistent failure (manual fix)
Service downResume from durable state when up

12. Managing Transaction Logs

ElementPurpose
Saga logPersisted state of each step
Audit trailWho/what/when for compliance
ReplayRecover after crash
RetentionMatch regulatory/business needs