Model transactional outbox and saga patterns
Model transactional outbox and saga patterns
A transactional outbox stores a business change and its outgoing event in the same local transaction. A relay publishes committed events and marks them sent only after confirmation; a crash between publication and marking may cause redelivery. A saga coordinates multiple local transactions and uses business-specific compensation when a later step fails.
package main
import ( "fmt")
type Event struct { ID string Sent bool}type State struct { Orders int Outbox []Event}
func add(s State, id string, commit bool) State { if !commit { return s } next := State{Orders: s.Orders + 1, Outbox: append([]Event(nil), s.Outbox...)} next.Outbox = append(next.Outbox, Event{ID: id}) return next}func main() { s := State{} s = add(s, "a", false) fmt.Println(s.Orders, len(s.Outbox)) s = add(s, "b", true) fmt.Println(s.Orders, s.Outbox[0].ID, s.Outbox[0].Sent)}The pure state transition models all-or-nothing commitment, not a database transaction. The new state includes both order and event or neither. Assume unique order IDs. In a real SQL transaction, insert the order and outbox row with the same Tx, commit, and let a separate relay read only committed rows. Do not mark an event sent before broker confirmation.
Expected output:
0 01 b falseCompensate a successful earlier step
package main
import ( "fmt")
func reserveThenCharge(stock int, chargeOK bool) (int, string) { if stock <= 0 { return stock, "unavailable" } stock-- if !chargeOK { stock++ return stock, "compensated" } return stock, "complete"}func main() { n, s := reserveThenCharge(3, false) fmt.Println(n, s) n, s = reserveThenCharge(3, true) fmt.Println(n, s)}Releasing a reservation compensates for a failed charge in this model. A real charge timeout may be ambiguous: reconcile the charge before compensating. Compensation is another effect that can fail and may not restore the world exactly. Persist saga progress, make forward and compensating actions idempotent, and define manual recovery for stuck workflows.
Expected output:
3 compensated2 completeTry it locally
Model a relay that marks an event sent only on confirmed publication. For a fresh event, apply false then true and print the sent status after each.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Distributed services 07: Model transactional outbox and saga patterns
Check the lesson objective before moving on.
Why put the outbox row in the same transaction?
What is saga compensation?