Course contentsShow
← C#
Lesson 1556 of 1,90814. Background Work and MessagingFree lesson

Choosing Between Events and Commands

Decide when to emit a domain event versus sending a direct command to another service.

In this lesson, you will learn how to distinguish between domain events and commands to ensure your distributed services remain decoupled yet functional.

The Conceptual Distinction

The core difference lies in the intent and the caller's knowledge of the downstream system.

  • Commands represent a direct request: "Do this." You are directing a specific service to perform an action. You expect that service to validate the request and succeed. Use these when you have a clear dependency and you are explicitly telling another service how to behave.
  • Events represent a historical fact: "This happened." You are broadcasting that a change occurred within your domain. You do not know (or care) who is listening or how they react. Use these to communicate state changes to multiple downstream subscribers without creating a tight coupling.

Deciding with Code

Imagine an OrderService. When an order is placed, you must decide how to trigger the InventoryService.

Using a Command:

// Explicitly directing the InventoryService to act
await _inventoryClient.SendAsync(new ReserveStockCommand(orderId, items));

Use this if the inventory deduction is a strict requirement for the OrderService to finish its own internal task. The caller is aware of the InventoryService and expects a successful outcome.

Using an Event:

// Broadcasting a fact to the ether
await _eventBus.PublishAsync(new OrderPlacedEvent(orderId, items));

Use this when multiple services (Inventory, Shipping, Analytics) need to react independently. The OrderService doesn't know the InventoryService exists; it simply reports the fact that an order was placed. This preserves your service boundaries and prevents the "distributed monolith" where one service knows too much about the internal business rules of another.

When to choose which?

Ask yourself: "If I add a new feature that needs this information, do I need to change the code of my current service?"

  • If yes, you are likely using Commands and have created a tight coupling.
  • If no, and you can simply add a new subscriber to your message bus, you are leveraging the power of Events.

Key Takeaway: Use Commands to direct a specific action with an expected outcome, and use Events to broadcast facts that allow autonomous services to react at their own discretion.