Saga Pattern em Go


Em microservices, um “checkout” costuma envolver vários serviços (ex.: estoque, pagamento, entrega). O problema: você não consegue (ou não deve) abrir uma transação ACID única envolvendo múltiplos bancos/serviços. O Saga Pattern resolve isso usando consistência eventual:
Um step é uma operação que:
Por isso, normalmente modelamos cada step com dois métodos:
Do() → ação principalCompensate() → desfaz a ação principal (best effort)Compensação não é rollback transacional:
Existe um orquestrador (um serviço ou módulo) que:
Prós:
Contras:
Cada serviço publica eventos e outros reagem. Prós: mais desacoplado. Contras: mais difícil de rastrear/depurar no início.
Idempotência
Do() e Compensate() devem poder rodar mais de uma vez sem quebrar.Persistir progresso (state)
Retries + backoff
Compensate(), pois falhar em compensar é crítico.Timeouts e cancelamento com context.Context
Observabilidade
Fluxo:
Se falhar no step 3:
Abaixo, um exemplo didático (simulado em memória), mas com comentários bem detalhados.
package main import ( "context" "errors" "fmt" "log" "time" ) // Step é a unidade do Saga. // - Do: executa a ação principal. // - Compensate: desfaz a ação principal (best effort). type Step interface { Name() string Do(ctx context.Context) error Compensate(ctx context.Context) error } // Saga executa steps em ordem. Se falhar, compensa em ordem reversa. type Saga struct { steps []Step } // Add registra steps na ordem em que devem rodar. func (s *Saga) Add(steps ...Step) { s.steps = append(s.steps, steps...) } // Execute executa o fluxo principal. // Em caso de falha, chama compensate() com os steps que já foram executados. func (s *Saga) Execute(ctx context.Context) error { var executed []Step // guarda os steps que concluíram com sucesso for _, step := range s.steps { log.Printf("[saga] running step: %s", step.Name()) if err := step.Do(ctx); err != nil { log.Printf("[saga] step failed: %s: %v", step.Name(), err) // Compensa apenas o que já foi executado. s.compensate(ctx, executed) return fmt.Errorf("saga failed at step %s: %w", step.Name(), err) } // Só entra aqui se o step concluiu bem. executed = append(executed, step) } log.Println("[saga] completed successfully") return nil } // compensate desfaz em ordem reversa. // Observação: compensação pode falhar; em produção você guardaria e retentaria depois. func (s *Saga) compensate(ctx context.Context, executed []Step) { log.Println("[saga] starting compensation...") for i := len(executed) - 1; i >= 0; i-- { step := executed[i] log.Printf("[saga] compensating: %s", step.Name()) if err := step.Compensate(ctx); err != nil { // Em produção: persistir falha da compensação + reprocessar. log.Printf("[saga] compensation failed: %s: %v", step.Name(), err) } } log.Println("[saga] compensation finished") } // ----------------- Steps concretos (simulados) ----------------- // ReserveStockStep simula reservar estoque. type ReserveStockStep struct { stock map[string]int product string qty int reserved bool // serve para sabermos se precisamos compensar } func (s *ReserveStockStep) Name() string { return "reserve-stock" } func (s *ReserveStockStep) Do(ctx context.Context) error { // Simula latência de rede/DB select { case <-ctx.Done(): return ctx.Err() case <-time.After(120 * time.Millisecond): } available := s.stock[s.product] if available < s.qty { return fmt.Errorf("insufficient stock: have=%d want=%d", available, s.qty) } s.stock[s.product] -= s.qty s.reserved = true log.Printf("[stock] reserved %d of %s (remaining=%d)", s.qty, s.product, s.stock[s.product]) return nil } func (s *ReserveStockStep) Compensate(ctx context.Context) error { // Idempotência básica: se não reservou, não compensa. if !s.reserved { return nil } select { case <-ctx.Done(): return ctx.Err() case <-time.After(80 * time.Millisecond): } s.stock[s.product] += s.qty s.reserved = false log.Printf("[stock] released %d of %s (compensation)", s.qty, s.product) return nil } // ChargePaymentStep simula cobrar pagamento. type ChargePaymentStep struct { charged bool amount float64 } func (p *ChargePaymentStep) Name() string { return "charge-payment" } func (p *ChargePaymentStep) Do(ctx context.Context) error { select { case <-ctx.Done(): return ctx.Err() case <-time.After(180 * time.Millisecond): } // Aqui poderia falhar por cartão recusado, gateway fora, etc. p.charged = true log.Printf("[payment] charged amount=%.2f", p.amount) return nil } func (p *ChargePaymentStep) Compensate(ctx context.Context) error { if !p.charged { return nil } select { case <-ctx.Done(): return ctx.Err() case <-time.After(110 * time.Millisecond): } p.charged = false log.Printf("[payment] refunded amount=%.2f (compensation)", p.amount) return nil } // CreateShippingStep simula criar uma entrega. type CreateShippingStep struct { created bool fail bool } func (s *CreateShippingStep) Name() string { return "create-shipping" } func (s *CreateShippingStep) Do(ctx context.Context) error { select { case <-ctx.Done(): return ctx.Err() case <-time.After(140 * time.Millisecond): } if s.fail { // Simula o caso típico: provedor indisponível return errors.New("shipping provider unavailable") } s.created = true log.Printf("[shipping] created") return nil } func (s *CreateShippingStep) Compensate(ctx context.Context) error { // Nem sempre existe compensação; depende do domínio. // Aqui supomos que se criou, dá para cancelar. if !s.created { return nil } select { case <-ctx.Done(): return ctx.Err() case <-time.After(90 * time.Millisecond): } s.created = false log.Printf("[shipping] canceled (compensation)") return nil } func main() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() // Estoque simulado stock := map[string]int{ "notebook": 3, } // Monta o Saga (orquestração) saga := &Saga{} // Criamos os steps com os dados que precisam. reserve := &ReserveStockStep{stock: stock, product: "notebook", qty: 2} payment := &ChargePaymentStep{amount: 1999.90} shipping := &CreateShippingStep{fail: true} // forçando falha para ver compensação saga.Add(reserve, payment, shipping) if err := saga.Execute(ctx); err != nil { log.Println("RESULT:", err) return } log.Println("RESULT: checkout completed") }
Se CreateShippingStep.Do() falha:
compensate().compensate() percorre os steps executados em ordem reversa:
ChargePaymentStep.Compensate() → estornaReserveStockStep.Compensate() → libera estoqueIsso é o “coração” do Saga.
Se quiser evoluir esse exemplo para produção, as próximas peças são:
sagas com saga_id, current_step, status, attempts)Do/CompensateSaga é um padrão essencial para orquestrar fluxos distribuídos com consistência eventual. Em Go, ele fica natural com interfaces simples (Do/Compensate) e um orquestrador que controla ordem, falhas e compensações.
Se você me disser seu cenário (ex.: checkout, criação de conta, provisionamento), eu adapto o exemplo para algo mais “real” com:
sagaIDIn microservices, a “checkout” typically spans multiple services (e.g., inventory, payment, shipping). The problem: you can’t realistically run a single ACID transaction across multiple databases/services. The Saga Pattern addresses this using eventual consistency:
A step is an operation that:
That’s why each step is usually modeled with two methods:
Do() → main actionCompensate() → undo the main action (best effort)Compensation is not a transactional rollback:
There is an orchestrator (a service/module) that:
Pros:
Cons:
Services react to events from others without a central coordinator. Pros: more decoupled. Cons: harder to trace end-to-end flows at the beginning.
Idempotency
Do() and Compensate() must be safe to execute multiple times.Persist progress (state)
Retries + backoff
Timeouts and cancellation via context.Context
Observability
Flow:
If step 3 fails:
Below is a didactic in-memory simulation with detailed comments.
package main import ( "context" "errors" "fmt" "log" "time" ) // Step is the unit of a Saga. // - Do: executes the main action. // - Compensate: undoes the main action (best effort). type Step interface { Name() string Do(ctx context.Context) error Compensate(ctx context.Context) error } // Saga runs steps in order. If a step fails, it compensates in reverse order. type Saga struct { steps []Step } // Add registers steps in the execution order. func (s *Saga) Add(steps ...Step) { s.steps = append(s.steps, steps...) } // Execute runs the main flow. // If a step fails, compensate() is called with the already executed steps. func (s *Saga) Execute(ctx context.Context) error { var executed []Step // steps that completed successfully for _, step := range s.steps { log.Printf("[saga] running step: %s", step.Name()) if err := step.Do(ctx); err != nil { log.Printf("[saga] step failed: %s: %v", step.Name(), err) // Compensate only what already succeeded. s.compensate(ctx, executed) return fmt.Errorf("saga failed at step %s: %w", step.Name(), err) } executed = append(executed, step) } log.Println("[saga] completed successfully") return nil } // compensate undoes steps in reverse order. // Note: compensations can fail; in production you’d persist failures and retry. func (s *Saga) compensate(ctx context.Context, executed []Step) { log.Println("[saga] starting compensation...") for i := len(executed) - 1; i >= 0; i-- { step := executed[i] log.Printf("[saga] compensating: %s", step.Name()) if err := step.Compensate(ctx); err != nil { // In production: persist this and reprocess later. log.Printf("[saga] compensation failed: %s: %v", step.Name(), err) } } log.Println("[saga] compensation finished") } // ----------------- Concrete steps (simulated) ----------------- // ReserveStockStep reserves stock. type ReserveStockStep struct { stock map[string]int product string qty int reserved bool // used to decide whether to compensate } func (s *ReserveStockStep) Name() string { return "reserve-stock" } func (s *ReserveStockStep) Do(ctx context.Context) error { // Simulate network/DB latency select { case <-ctx.Done(): return ctx.Err() case <-time.After(120 * time.Millisecond): } available := s.stock[s.product] if available < s.qty { return fmt.Errorf("insufficient stock: have=%d want=%d", available, s.qty) } s.stock[s.product] -= s.qty s.reserved = true log.Printf("[stock] reserved %d of %s (remaining=%d)", s.qty, s.product, s.stock[s.product]) return nil } func (s *ReserveStockStep) Compensate(ctx context.Context) error { // Basic idempotency: if nothing was reserved, nothing to undo. if !s.reserved { return nil } select { case <-ctx.Done(): return ctx.Err() case <-time.After(80 * time.Millisecond): } s.stock[s.product] += s.qty s.reserved = false log.Printf("[stock] released %d of %s (compensation)", s.qty, s.product) return nil } // ChargePaymentStep charges a payment. type ChargePaymentStep struct { charged bool amount float64 } func (p *ChargePaymentStep) Name() string { return "charge-payment" } func (p *ChargePaymentStep) Do(ctx context.Context) error { select { case <-ctx.Done(): return ctx.Err() case <-time.After(180 * time.Millisecond): } // Could fail due to declined card, gateway outage, etc. p.charged = true log.Printf("[payment] charged amount=%.2f", p.amount) return nil } func (p *ChargePaymentStep) Compensate(ctx context.Context) error { if !p.charged { return nil } select { case <-ctx.Done(): return ctx.Err() case <-time.After(110 * time.Millisecond): } p.charged = false log.Printf("[payment] refunded amount=%.2f (compensation)", p.amount) return nil } // CreateShippingStep creates a shipping order. type CreateShippingStep struct { created bool fail bool } func (s *CreateShippingStep) Name() string { return "create-shipping" } func (s *CreateShippingStep) Do(ctx context.Context) error { select { case <-ctx.Done(): return ctx.Err() case <-time.After(140 * time.Millisecond): } if s.fail { // Typical failure: provider unavailable return errors.New("shipping provider unavailable") } s.created = true log.Printf("[shipping] created") return nil } func (s *CreateShippingStep) Compensate(ctx context.Context) error { // Not every domain needs a compensation here. // In this example, if it was created, we can cancel it. if !s.created { return nil } select { case <-ctx.Done(): return ctx.Err() case <-time.After(90 * time.Millisecond): } s.created = false log.Printf("[shipping] canceled (compensation)") return nil } func main() { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() // Simulated stock stock := map[string]int{ "laptop": 3, } // Build the Saga (orchestration) saga := &Saga{} reserve := &ReserveStockStep{stock: stock, product: "laptop", qty: 2} payment := &ChargePaymentStep{amount: 1999.90} shipping := &CreateShippingStep{fail: true} // force failure to demonstrate compensation saga.Add(reserve, payment, shipping) if err := saga.Execute(ctx); err != nil { log.Println("RESULT:", err) return } log.Println("RESULT: checkout completed") }
If CreateShippingStep.Do() fails:
compensate().compensate() runs the executed steps in reverse order:
ChargePaymentStep.Compensate() → refundReserveStockStep.Compensate() → release stockThat’s the core of a Saga.
To move closer to real-world usage, you typically add:
sagas table with saga_id, current_step, status, attempts)Do/CompensateThe Saga Pattern is essential for orchestrating distributed workflows with eventual consistency. In Go, it maps cleanly to small interfaces (Do/Compensate) and an orchestrator that handles ordering, failures, and compensations.
If you share your concrete flow (checkout, account creation, provisioning, etc.), I can adapt the example to a more “real” setup with sagaID, persisted state, retries/backoff, and structured logs per step.