Principle:4thfever Cultivation world simulator Query Command Separation
| Knowledge Sources | |
|---|---|
| Domains | API_Design, Software_Architecture |
| Last Updated | 2026-10-22 14:00 GMT |
Overview
An API design pattern that separates read-only query endpoints from state-mutating command endpoints, enabling independent scaling, distinct middleware (caching vs. serialization), and a unified response contract for external agent integration.
Description
Query-Command Separation (a pragmatic form of CQRS) addresses the problem of exposing a complex simulation's state to external agents (AI controllers, tools) while maintaining safety and clarity. The pattern:
- Query endpoints (`GET /api/v1/query/*`): read world state, events, entity details, rankings, saves. These never modify state and can be called freely.
- Command endpoints (`POST /api/v1/command/*`): start/load games, create/delete avatars, set phenomena, pause/resume, save, roleplay interactions. All mutations are serialized through a runtime lock.
- Unified response contract: all endpoints return `{"ok": true, "data": ...}` on success, or structured error objects with code/message/details on failure.
This separation allows:
- Query endpoints to be served without acquiring the mutation lock
- Command endpoints to be throttled, logged, and serialized independently
- External agents to observe freely but intervene through a controlled channel
- Clear documentation: each endpoint is unambiguously a read or a write
Usage
Use this principle when:
- Designing an API for external agents to observe and control a simulation
- Read operations vastly outnumber writes and should not contend with mutation locks
- You need a stable, versioned API surface (`/api/v1/*`) that external integrations can depend on
- Errors should be structured and machine-parseable, not generic HTTP error strings
Theoretical Basis
The core constraint is the read-write segregation invariant:
# Abstract algorithm description (NOT real implementation)
# Query: pure read, no side effects
@router.get("/api/v1/query/world/state")
def get_world_state():
return ok_response(query_service.get_world_state())
# Command: mutation, serialized through lock
@router.post("/api/v1/command/avatar/create")
async def create_avatar(req: CreateAvatarRequest):
return ok_response(
await command_service.create_avatar(req) # runs inside runtime.run_mutation()
)
# Unified contract
def ok_response(data):
return {"ok": True, "data": data}
def raise_public_error(*, status_code, code, message, details=None):
raise HTTPException(status_code, detail={
"code": code,
"message": message,
"details": details or {},
})
Key design properties:
- Router factory pattern: routers are created by factory functions that accept callable dependencies, enabling both service-based and legacy-handler-based wiring
- Service delegation: the router checks if a `query_service` or `command_service` is provided and delegates; otherwise falls back to individual handler functions
- Pydantic models: command endpoints use Pydantic `BaseModel` subclasses for request validation
- Error contract: errors use `raise_public_error` with a machine-readable `code` field
Practical Guide
When implementing query-command separation:
- Version the namespace: use `/api/v1/` prefix so breaking changes can introduce `/api/v2/` without disrupting existing integrations
- Use factory functions for routers: pass dependencies as callables, not module-level imports, to allow testing and configuration reload
- Validate with Pydantic: all command request bodies should be Pydantic models for automatic validation
- Document the error contract: every error should have a stable `code` string that external agents can switch on
- Don't put business logic in routers: routers should only delegate to services; the service layer contains the use-case logic