Golang / GoLang System Architecture and Testing Interview Questions
How do CQRS and event sourcing apply to Go microservice architecture?
CQRS (Command Query Responsibility Segregation) separates reads and writes into separate models. Event Sourcing stores every state change as an event — the current state is derived by replaying events. Both patterns appear in high-scale Go systems.
// CQRS: separate command and query handlers
// Command: mutates state, returns error
type CreateOrderCommand struct {
UserID string
ProductID string
Quantity int
}
type OrderCommandHandler struct{ eventStore EventStore }
func (h *OrderCommandHandler) Handle(
ctx context.Context, cmd CreateOrderCommand,
) error {
event := OrderCreatedEvent{
OrderID: uuid.New().String(),
UserID: cmd.UserID,
ProductID: cmd.ProductID,
Quantity: cmd.Quantity,
CreatedAt: time.Now(),
}
return h.eventStore.Append(ctx, event.OrderID, event)
}
// Query: reads from a projection (read model)
type OrderQueryHandler struct{ readDB *sql.DB }
func (h *OrderQueryHandler) GetOrder(
ctx context.Context, orderID string,
) (*OrderView, error) {
// Read from denormalised view optimised for queries
row := h.readDB.QueryRowContext(ctx,
"SELECT id, status, total, user_name FROM order_views WHERE id=$1",
orderID)
var view OrderView
return &view, row.Scan(&view.ID, &view.Status, &view.Total, &view.UserName)
}
// Event Sourcing: replay events to reconstruct state
type Order struct {
ID string
Status string
Items []OrderItem
version int
}
func ReplayOrder(ctx context.Context, store EventStore, id string) (*Order, error) {
events, err := store.Load(ctx, id)
if err != nil { return nil, err }
order := &Order{ID: id}
for _, event := range events {
order.apply(event) // deterministically mutate state
order.version++
}
return order, nil
}
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...
