Golang / GoLang System Architecture and Testing Interview Questions
How do you implement the Saga pattern for distributed transactions in Go?
Distributed transactions that span multiple services cannot use traditional 2-phase commit without creating tight coupling and availability issues. The Saga pattern decomposes a transaction into a sequence of local transactions, each publishing an event. Failures trigger compensating transactions.
// Choreography-based saga: services react to events
// OrderService publishes OrderCreated
type OrderCreatedEvent struct {
OrderID string `json:"order_id"`
UserID string `json:"user_id"`
Amount float64 `json:"amount"`
ProductID string `json:"product_id"`
}
// PaymentService consumes OrderCreated, publishes PaymentProcessed or PaymentFailed
func (s *PaymentService) HandleOrderCreated(ctx context.Context,
event OrderCreatedEvent) error {
charged, err := s.stripe.Charge(ctx, event.UserID, event.Amount)
if err != nil {
// Publish compensating event for OrderService to cancel the order
return s.publisher.Publish(ctx, PaymentFailedEvent{
OrderID: event.OrderID,
Reason: err.Error(),
})
}
return s.publisher.Publish(ctx, PaymentProcessedEvent{
OrderID: event.OrderID,
ChargeID: charged.ID,
})
}
// InventoryService consumes PaymentProcessed, publishes StockReserved or StockUnavailable
// OrderService listens to StockReserved → fulfillment
// OrderService listens to StockUnavailable → refund (another compensating event)
// Outbox pattern: ensure event is published atomically with DB write
func (s *OrderService) CreateOrder(ctx context.Context, req OrderRequest) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil { return err }
defer tx.Rollback()
// Write order to DB
orderID := uuid.New().String()
tx.ExecContext(ctx, "INSERT INTO orders ...", orderID, req.UserID)
// Write event to outbox table in SAME transaction
eventData, _ := json.Marshal(OrderCreatedEvent{OrderID: orderID})
tx.ExecContext(ctx,
"INSERT INTO outbox (event_type, payload) VALUES ($1, $2)",
"order.created", eventData)
return tx.Commit()
// Separate process reads outbox and publishes to message queue
}Outbox pattern solves the dual-write problem: writing to the DB and publishing to a message queue are two separate operations — either can fail. Writing both to the same DB transaction (with the event in an outbox table) makes them atomic; a relay process then publishes to the queue and deletes from outbox.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
