Microservices Communication Patterns (Saga, Circuit Breaker) · Lekcja

Zaawansowana logika kompensacji

Proszę opracować zaawansowaną logikę kompensacji dla złożonych scenariuszy, zapewniając spójność danych nawet w przypadku awarii.

Lekcja 3 z 410 kroki

Zaawansowana logika kompensacji to bezpłatna lekcja Microservices Communication Patterns (Saga, Circuit Breaker) na CoddyKit. To lekcja 3 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Microservices Communication Patterns (Saga, Circuit Breaker), a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Microservices Communication Patterns (Saga, Circuit Breaker) zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Deeper Compensation Needs

In previous lessons, we learned about the Saga pattern and how compensation steps reverse actions in case of failure. But what happens when failures are more complex?

Simple rollbacks aren't always enough in a distributed system. We need advanced compensation logic to handle intricate scenarios and ensure data consistency.

When Simple Isn't Enough

Advanced compensation becomes vital when:

  • Partial Success: Some steps completed, others failed, leading to an inconsistent state.
  • External Systems: Interactions with third-party services that don't offer immediate rollbacks.
  • Non-Idempotent Operations: Actions that can't simply be undone by re-running a basic compensation step.
  • Complex Business Rules: Compensation logic that depends on specific conditions or data.

Designing Idempotent Compensation

A crucial aspect of robust compensation is making it idempotent. This means running the compensation action multiple times will have the same effect as running it once.

This is vital for reliability, as messages can be duplicated or retried. Your compensation logic should always check the current state before attempting to reverse an action.

Try running this example:

public class OrderService {

    private boolean isRefunded(String orderId) {
        // Simulate checking a database or payment system
        System.out.println("Checking if order " + orderId + " is already refunded...");
        // In a real system, this would query a persistent store
        return false; // For demo, assume not refunded initially
    }

    public void compensateOrderPayment(String orderId) {
        System.out.println("Attempting compensation for order: " + orderId);
        if (isRefunded(orderId)) {
            System.out.println("Order " + orderId + " already refunded. No action needed.");
            return;
        }
        // Simulate refunding logic
        System.out.println("Initiating refund for order: " + orderId);
        // ... actual refund processing ...
        System.out.println("Refund processed for order: " + orderId);
        // In a real system, this would update the 'refunded' status
    }

    public static void main(String[] args) {
        OrderService service = new OrderService();
        String orderId = "ORDER-123";
        service.compensateOrderPayment(orderId);
        System.out.println("\nSimulating a retry or duplicate message:");
        service.compensateOrderPayment(orderId); // Should ideally be idempotent
    }
}

State-Dependent Compensation

Sometimes, the compensation action itself depends on the specific failure or the current state of the system. For example, if an inventory item was reserved but not shipped, you might just release the reservation, rather than processing a full refund.

This requires adding conditional checks within your compensation logic.

Try running this example:

public class InventoryService {

    private enum InventoryState { RESERVED, SHIPPED, AVAILABLE }

    private InventoryState getItemState(String itemId) {
        // Simulate checking inventory status from a database
        System.out.println("Checking state for item: " + itemId);
        // In a real system, this would query a persistent store
        return InventoryState.RESERVED; // Let's assume it's reserved for this demo
    }

    public void compensateInventoryReservation(String itemId) {
        System.out.println("Attempting compensation for item: " + itemId);
        InventoryState currentState = getItemState(itemId);

        if (currentState == InventoryState.SHIPPED) {
            System.out.println("Item " + itemId + " was already shipped. Cannot directly un-reserve.");
            System.out.println("Manual intervention or a different compensation for shipped items might be needed.");
        } else if (currentState == InventoryState.RESERVED) {
            System.out.println("Item " + itemId + " is reserved. Releasing reservation.");
            // Simulate releasing the reservation
            System.out.println("Reservation released for item: " + itemId);
        } else {
            System.out.println("Item " + itemId + " is not reserved or is available. No action needed.");
        }
    }

    public static void main(String[] args) {
        InventoryService service = new InventoryService();
        String itemId = "ITEM-456";
        service.compensateInventoryReservation(itemId);
    }
}

External Systems & Compensation

Compensating actions that involve external third-party services (e.g., payment gateways, shipping carriers, CRM systems) introduce unique challenges.

  • No Direct Rollback: You can't directly "undo" an external API call. You must use their provided compensation mechanisms (e.g., a refund API, a cancellation API).
  • Asynchronous Nature: External systems might process requests asynchronously, making it harder to determine the exact state for compensation.
  • Rate Limits & Availability: Compensation calls can fail due to external system issues, requiring retries and robust error handling.

When Humans Step In

Despite our best efforts, some complex failures or critical inconsistencies cannot be fully resolved by automated compensation logic alone. This is where manual intervention or "human sagas" come into play.

A human saga involves notifying an operator or support team when an automated compensation fails or when the system detects an unrecoverable state, allowing them to manually rectify the issue.

  • Alerting: Set up alerts for failed compensation steps.
  • Dashboards: Provide visibility into pending or failed sagas.
  • Tools: Develop internal tools for manual data correction or re-triggering compensation.

Evolving Compensation

Microservices evolve, and so do their data models and business logic. This means your compensation logic must also evolve. What happens to a saga that started with an older version of your service when a failure occurs after an update?

Strategies for versioning compensation:

  • Backward Compatibility: Design new compensation logic to handle older saga states.
  • Saga Versioning: Store the version of the saga definition with the saga's state.
  • Migration: For significant changes, migrate in-flight sagas to the new compensation logic if possible.

Keeping an Eye on Compensation

A compensation step failing is a critical event. If compensation itself fails, your system could be left in an inconsistent state, leading to data corruption or business impact.

It's crucial to:

  • Log Compensation Attempts: Record every compensation action, its status, and any errors.
  • Monitor Failure Rates: Track how often compensation steps fail.
  • Set Up Alerts: Immediately notify operations teams if compensation failures exceed thresholds.
  • Trace Compensation Paths: Use distributed tracing to understand why compensation failed.

Compensation Challenges

Which of the following are key considerations when designing advanced compensation logic for microservices?

Recap: Sophisticated Rollbacks

We've explored how to move beyond basic rollbacks to implement advanced compensation logic in your microservices.

  • We emphasized idempotency and conditional logic for robust compensation.
  • We discussed the complexities of external systems and the necessity of manual intervention for critical failures.
  • Finally, we covered strategies for versioning and monitoring compensation to ensure long-term consistency and reliability.

Mastering these techniques is key to building truly resilient distributed systems.

Bezpłatny start

Ucz się Microservices Communication Patterns (Saga, Circuit Breaker) dzięki korepetycjom AI — za darmo

Pisz i uruchamiaj kod w przeglądarce, otrzymuj natychmiastową pomoc od korepetytora AI dostępnego 24/7 i kontynuuj naukę w sieci lub w aplikacji.

Kursy
12
Lekcje
48

Często zadawane pytania

Czy lekcja „Zaawansowana logika kompensacji” jest bezpłatna?

Tak — pełny tekst „Zaawansowana logika kompensacji” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Microservices Communication Patterns (Saga, Circuit Breaker), przejdź na CoddyKit PRO. Kurs Microservices Communication Patterns (Saga, Circuit Breaker) zawiera 4 lekcji w sumie.

Co nauczysz się w „Zaawansowana logika kompensacji”?

Proszę opracować zaawansowaną logikę kompensacji dla złożonych scenariuszy, zapewniając spójność danych nawet w przypadku awarii. Ćwiczysz Microservices Communication Patterns (Saga, Circuit Breaker) z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Microservices Communication Patterns (Saga, Circuit Breaker)?

Nie wymagamy żadnego doświadczenia. Microservices Communication Patterns (Saga, Circuit Breaker) w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 3 z 4.

Ile czasu zajmuje lekcja „Zaawansowana logika kompensacji”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Microservices Communication Patterns (Saga, Circuit Breaker)?

Tak. Każda lekcja Microservices Communication Patterns (Saga, Circuit Breaker) zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Zapewnianie idempotencji w sagach
  2. Strategie ponawiania prób dla sag
  3. Zaawansowana logika kompensacji
  4. Blokady semantyczne i współbieżne sagi
← Powrót do Microservices Communication Patterns (Saga, Circuit Breaker)