Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is the Saga pattern for distributed transactions? Distributed transactions के लिए Saga pattern क्या है?

Answer

Saga pattern manages long-running distributed transactions by breaking them into local transactions coordinated through events. Two approaches: choreography (events trigger actions) and orchestration (central coordinator). Handles failures with compensating transactions.

// Saga Pattern - Orchestration approach

// Events
public class OrderCreatedEvent {
    private String orderId;
    private double amount;
}

public class PaymentProcessedEvent {
    private String orderId;
    private String paymentId;
}

public class OrderFailedEvent {
    private String orderId;
    private String reason;
}

// Order Service
@Service
public class OrderService {
    @Autowired
    private KafkaTemplate<String, OrderCreatedEvent> kafkaTemplate;
    
    public void createOrder(Order order) {
        // Create order
        kafkaTemplate.send('orders', new OrderCreatedEvent(
            order.getId(), order.getAmount()));
    }
}

// Payment Service (listens to OrderCreatedEvent)
@Service
public class PaymentService {
    @KafkaListener(topics = 'orders', groupId = 'payment-service')
    public void processPayment(OrderCreatedEvent event) {
        try {
            // Process payment
            kafkaTemplate.send('payments', new PaymentProcessedEvent(
                event.getOrderId(), 'PAY-123'));
        } catch (Exception e) {
            // Publish compensation event
            kafkaTemplate.send('order-failures', new OrderFailedEvent(
                event.getOrderId(), e.getMessage()));
        }
    }
}

// Saga Orchestrator (centralized coordinator)
@Service
public class OrderSagaOrchestrator {
    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;
    
    public void startSaga(Order order) {
        // Step 1: Reserve inventory
        kafkaTemplate.send('inventory', order);
    }
    
    @KafkaListener(topics = 'inventory-reserved')
    public void onInventoryReserved(InventoryReservedEvent event) {
        // Step 2: Process payment
        kafkaTemplate.send('payments', event.getOrder());
    }
    
    @KafkaListener(topics = 'payment-failed')
    public void onPaymentFailed(PaymentFailedEvent event) {
        // Step 3: Compensate - release inventory
        kafkaTemplate.send('inventory', new ReleaseInventoryCommand(
            event.getOrderId()));
    }
}

// Saga Pattern Benefits:
// 1. Handles distributed transactions
// 2. Ensures data consistency
// 3. Handles failures gracefully
// 4. No 2PC (two-phase commit) needed
// 5. Event-driven architecture

// Two approaches:
// Choreography - services listen and react
// Orchestration - central orchestrator coordinates
Saga Pattern:

Problem: Distributed transactions में atomicity ensure करना मुश्किल

Solution: Break into local transactions
Each service अपना transaction manage करे

Compensating Transactions:
- अगर failure हो, undo करना
- Rollback like behavior

Orchestration:
- Central coordinator सभी को direct करे
- Easier to track
- Single point of failure

Choreography:
- Services events को listen करते हैं
- Loosely coupled
- Complex to debug

Steps:
1. Service A completes
2. Publishes event
3. Service B listens
4. If failure, compensation triggered

Was this answer clear?