Request Handlers¶
Overview¶
Request handlers process commands (write operations) and queries (read operations) in your CQRS application. They are the core of your business logic and are automatically resolved through the Dependency Injection container configured in Bootstrap.
Coding agents pick this path with cqrs-setup: both a command and a query are cqrs.Request, and the catalog is Agent skills.
Testing a command records requests and invocations. Testing a query leaves handled and published empty.
| Concept | Description | Can Emit Events |
|---|---|---|
| Commands | Modify system state | ✅ Yes |
| Queries | Read data without side effects | ❌ No (typically) |
| Handlers | Implement business logic, resolved via DI | Depends on type |
Prerequisites
Before creating handlers, ensure you've configured Bootstrap and understand Dependency Injection.
Related Topics
- Request / Response Types — Different types for requests and responses (Pydantic, Dataclasses, attrs, etc.)
- Stream Handling — For incremental processing
- Chain of Responsibility — For sequential handler chains
- Saga Pattern — For distributed transactions with compensation
- Event Handling — For processing events emitted by command handlers
- Request Handler Fallback — Fallback mechanism for resilient command/query handling
Request handlers can be divided into two main types:
Command Handler¶
Command Handler executes the received command. The logic of the handler may include, for example, modifying the state of the domain model. As a result of executing the command, an event may be produced to the broker.
| Aspect | Description |
|---|---|
| Purpose | Execute write operations, modify system state |
| Return Value | Optional (can return None or a response) |
| Events | Can emit domain events via events property |
| Handler Type | RequestHandler[Command] when the command is Request[None] or Request[Result] |
Return Value
By default, the command handler does not return any result, but it is not mandatory. You can return a response if needed.
Command Handler Characteristics
- Modifies state: Changes the system's state
- Can emit events: Returns events through
eventsproperty - Idempotent: Should be idempotent when possible
- Transactional: Often wrapped in database transactions
import cqrs
from cqrs.handlers.request import RequestHandler
class JoinMeetingCommand(cqrs.Request[None]):
user_id: str
meeting_id: str
class JoinMeetingCommandHandler(RequestHandler[JoinMeetingCommand]):
def __init__(self, meetings_api: MeetingAPIProtocol) -> None:
self._meetings_api = meetings_api
async def handle(self, request: JoinMeetingCommand):
await self._meetings_api.join_user(request.user_id, request.meeting_id)
Do not add -> None on handle in new code: Request[None] already says the method returns None.
Query Handler¶
Query Handler returns a representation of the requested data, for example, from the read model.
| Aspect | Description |
|---|---|
| Purpose | Read data without modifying system state |
| Return Value | Always returns a response |
| Events | Typically does not emit events |
| Handler Type | RequestHandler[Query] when the query is Request[QueryResult] |
Read Model
The read model can be constructed based on domain events produced by the Command Handler. This allows for optimized read operations.
Query Handler Characteristics
- Read-only: Does not modify system state
- No side effects: Should not have side effects
- Optimized: Can use read models optimized for specific queries
- Fast: Should be fast and efficient
import cqrs
from cqrs.handlers.request import RequestHandler
class ReadMeetingQueryResult(cqrs.Response):
link: str
meeting_id: str
class ReadMeetingQuery(cqrs.Request[ReadMeetingQueryResult]):
meeting_id: str
class ReadMeetingQueryHandler(RequestHandler[ReadMeetingQuery]):
def __init__(self, meetings_api: MeetingAPIProtocol) -> None:
self._meetings_api = meetings_api
async def handle(self, request: ReadMeetingQuery):
link = await self._meetings_api.get_link(request.meeting_id)
return ReadMeetingQueryResult(link=link, meeting_id=request.meeting_id)
await mediator.send(ReadMeetingQuery(...)) has type ReadMeetingQueryResult. Do not add -> ReadMeetingQueryResult on handle.
Legacy (still supported). The two-argument form still works. Copy the one-argument form above.
class ReadMeetingQueryHandler(cqrs.RequestHandler[ReadMeetingQuery, ReadMeetingQueryResult]):
async def handle(self, request: ReadMeetingQuery) -> ReadMeetingQueryResult:
...
A runnable example is examples/events/typed_request_handler.py. Register with mapper.bind(RequestType, Handler). One handler per request type: a second bind raises KeyError.