Commands

Commands are messages that express the intent to change application state. They represent actions that should happen, such as "create an order," "update a user profile," or "approve a payment." In Axon Framework, commands are a fundamental building block of your application architecture.

Command-centric approach

Axon Framework takes a messaging-centric approach to application design. Commands are central to how your application processes user actions and external events. The framework provides comprehensive support for:

  • Dispatching commands - Sending commands from controllers, APIs, or other handlers

  • Handling commands - Processing commands to validate requests and apply changes

  • Routing commands - Directing commands to the appropriate handler based on routing keys

  • Coordinating changes - Managing state changes across one or more components

This approach emphasizes what you want to accomplish (commands) rather than how you structure your domain model.

Command handlers: stateful and stateless

Command handlers fall into two main categories based on how they manage state:

Stateful handlers (most common)

Handlers where Axon Framework manages the state lifecycle automatically. Axon loads the current state, invokes your handler, and persists any changes. Your handler focuses on business logic while Axon handles state management.

Examples: Order handlers, user account handlers, payment handlers

Stateless handlers

Handlers where state is not managed by Axon Framework. These handlers must query and manage state themselves when needed, typically by calling external services or databases directly within the handler.

Examples: Integration handlers that call external APIs, handlers that query read models, notification handlers

Managing state with entities

For stateful command handling, Axon Framework provides comprehensive entity support for state management. Entities are components that encapsulate state and the business logic that operates on that state.

Axon supports two approaches to entity state management:

  • Event-sourced entities - State derived from a sequence of events

  • State-stored entities - State persisted directly to a database

You can mix and match these approaches based on your needs. The choice depends on your specific requirements for state management, auditability, and consistency.

Alternatively, you can implement stateful handlers without using entities, managing state through your own custom mechanisms.

Subsections

A summary of the various sections is given below.

Sub-Section Purpose

Handling

How to write command handlers (stateless and stateful, with and without entities)

Dispatching

How to dispatch commands from your application code

Infrastructure

Command bus implementations, repositories, and other infrastructure components

Configuration

How to configure command handling in your application