Command Pattern (backend)
ELI5 — The Vibe Check
The command pattern turns requests into objects. Instead of calling a function directly, you create a 'command' object that describes what you want done — like writing an order slip at a restaurant instead of yelling at the chef. This lets you queue commands, undo them, log them, validate them, and route them anywhere.
Real Talk
In backend architecture, the Command pattern (especially in CQRS) encapsulates a write operation as an object containing all data needed for execution. Commands are named as imperatives (CreateOrder, CancelSubscription) and are handled by dedicated command handlers. This separates intent from execution, enabling validation, authorization, auditing, and async processing.
Show Me The Code
// Command
class CreateOrderCommand {
constructor(public customerId: string, public items: Item[]) {}
}
// Handler
class CreateOrderHandler {
async handle(cmd: CreateOrderCommand): Promise<Order> {
// validate, create order, publish events
}
}
When You'll Hear This
"Dispatch the CreateOrder command — the handler will validate and process it." / "Commands represent intent, events represent what actually happened."
Related Terms
Aggregate Root
An aggregate root is the boss entity that controls a group of related objects. Want to add an item to an order?
CQRS
CQRS says: the way you write data and the way you read data should be separate systems. Writing (commands) goes to one model optimized for transactions.
Domain Event
A domain event is something meaningful that happened in your business. Not 'row updated in users table' but 'UserRegistered' or 'OrderShipped.