State Management
Overview
State management defines where application state lives, how it changes, and how consistency is preserved across distributed components.
State Categories
- Request state: short-lived per operation
- Session state: user context across requests
- Domain state: persistent business records
- Derived state: computed projections and caches
flowchart TD
A[Client Request] --> B[API Service]
B --> C[(Primary Store)]
B --> D[(Cache Store)]
C --> E[Event Stream]
E --> F[(Read Model)]
Practical Example
A shopping application keeps cart session state in Redis and order state in PostgreSQL.
cartState:
store: redis
ttlSeconds: 1800
orderState:
store: postgresql
consistency: strong
This split keeps carts responsive while preserving transactional correctness for payments and orders.
Design Techniques
- Keep services stateless when possible
- Externalize session state for horizontal scaling
- Use optimistic concurrency for conflicting updates
- Emit domain events to synchronize projections
Common Pitfalls
- Storing critical business state only in cache
- Ignoring conflict handling in concurrent updates
- Mixing transient and durable state without clear ownership
Key Takeaways
- State location directly affects scalability and correctness.
- Session and domain state usually require different storage strategies.
- Clear ownership and consistency rules prevent data anomalies.