Lifecycle States, Valid Transitions, Invariants, and Time
State Machines, Invariants, and Temporal Semantics
Menggunakan state machine dan invariants untuk memodelkan lifecycle komersial yang defensible.
Part 004 — Lifecycle States, Valid Transitions, Invariants, and Time
Positioning
CPQ dan Quote-to-Order adalah kumpulan long-running lifecycles.
Entity tidak hanya memiliki data.
Mereka memiliki:
- state;
- valid transitions;
- guards;
- commands;
- events;
- time constraints;
- failure behavior;
- dan audit evidence.
Tanpa lifecycle model eksplisit, business rules tersebar di:
- controllers;
- UI buttons;
- workflow scripts;
- database triggers;
- event consumers;
- dan manual operations.
Core thesis: state machine yang baik memisahkan business state, processing state, dan integration state; menjaga invariants pada setiap transition; serta membuat time, retry, failure, dan recovery sebagai first-class domain concepts.
1. What a State Machine Is
A state machine defines:
- possible states;
- allowed transitions;
- triggering commands/events;
- guards;
- actions;
- and resulting events.
It answers:
What can happen now?
Who may cause it?
Under what conditions?
What becomes true afterward?
2. Why State Machines Matter in CPQ
CPQ and order lifecycles involve:
- drafts;
- approvals;
- customer waiting;
- expiry;
- asynchronous processing;
- partial completion;
- cancellation;
- retries;
- and manual recovery.
These cannot be modeled safely with a single free-form status field.
3. State versus Status
State
Has lifecycle semantics and controls behavior.
Status
May be a reporting or UI label.
Example:
Business State: ACCEPTED
Processing Status: ORDER_CONVERSION_RUNNING
Integration Status: EVENT_DELIVERY_RETRYING
4. State Machine Components
State
Current lifecycle condition.
Command
Request to perform action.
Guard
Condition that must be true.
Transition
Move from one state to another.
Action
Side effect or local mutation.
Event
Fact that transition occurred.
5. Command Example
Command:
SubmitQuoteForApproval
Current State:
DRAFT
Guard:
Quote complete and price valid
Result:
PENDING_APPROVAL
Event:
QuoteSubmittedForApproval
6. Guard versus Validation
Validation
Checks whether data or behavior is acceptable.
Guard
Determines whether a specific transition is allowed now.
A quote may be structurally valid but not allowed to accept because:
- approval expired;
- revision changed;
- or quote validity ended.
7. Transition Table
| Current State | Command | Guard | Next State | Event |
|---|---|---|---|---|
| Draft | SubmitForApproval | Complete | PendingApproval | QuoteSubmitted |
| PendingApproval | Approve | Authority valid | Approved | QuoteApproved |
| Approved | Present | Document ready | Presented | QuotePresented |
| Presented | Accept | Not expired | Accepted | QuoteAccepted |
| Presented | Expire | Validity ended | Expired | QuoteExpired |
8. Business State
Business state describes commercial meaning.
Examples:
- Draft;
- Approved;
- Presented;
- Accepted;
- Rejected;
- Expired;
- Cancelled.
9. Processing State
Processing state describes execution progress.
Examples:
- ValidationRunning;
- Repricing;
- ConversionRunning;
- DecompositionRunning;
- RecoveryPending.
It should not replace business state.
10. Integration State
Integration state describes external communication.
Examples:
- NotSent;
- Sent;
- Acknowledged;
- Failed;
- RetryScheduled.
Do not expose raw integration state as customer lifecycle status without translation.
11. Human Workflow State
Human workflow may have:
- Assigned;
- InReview;
- AwaitingInformation;
- Escalated;
- Completed.
This can be separate from quote state.
12. Composite State Risk
Combining all concerns creates explosion:
APPROVED_PENDING_EVENT_ACK
ACCEPTED_CONVERSION_FAILED
DRAFT_REPRICING
Prefer orthogonal state machines when concerns evolve independently.
13. Hierarchical State Machine
A hierarchical model can group states.
Example:
ACTIVE
- Draft
- PendingApproval
- Presented
TERMINAL
- Accepted
- Rejected
- Expired
- Cancelled
Use only when hierarchy has behavior meaning.
14. Parallel State Regions
Some lifecycles need concurrent dimensions.
Example quote:
- commercial state;
- approval state;
- document state.
Avoid one combinatorial enum.
15. Aggregate Invariant
An invariant must always hold for valid aggregate state.
Examples:
- quote total equals sum of price components;
- accepted quote revision is immutable;
- order item action MODIFY references existing inventory product;
- one active approval decision applies to current revision only.
16. Cross-Aggregate Invariant
Cross-aggregate invariants are harder.
Example:
One accepted quote creates at most one primary product order.
In distributed systems, enforce via:
- unique key;
- idempotency;
- process manager;
- and reconciliation.
17. Temporal Invariant
A temporal invariant includes time.
Examples:
- acceptance must occur before quote expiry;
- price validity must cover acceptance time;
- delegated approval authority must be active;
- cancellation is disallowed after irreversible fulfillment milestone.
18. Eventual Invariant
An eventual invariant allows temporary inconsistency.
Example:
Every activated inventory product eventually has corresponding billing activation.
Need:
- deadline;
- detection;
- reconciliation;
- and escalation.
19. Safety versus Liveness
Safety property
Something bad never happens.
Example:
- accepted quote is never modified.
Liveness property
Something good eventually happens.
Example:
- every accepted quote either creates order or reaches explicit conversion failure.
Both matter.
20. State Transition Ownership
Every transition should identify:
- actor;
- authority;
- aggregate;
- and owner.
A UI button is not authority.
21. Legal Transition versus Operational Capability
A transition may be valid but temporarily unavailable.
Example:
- quote may legally be cancelled;
- but cancellation service is degraded.
Separate business permission from operational availability.
22. Transition Reason
Material transitions should record reason.
Examples:
- rejection;
- cancellation;
- override;
- manual repair;
- expiry.
Reason should be stable and auditable.
23. Transition Evidence
Evidence may include:
- actor;
- timestamp;
- policy version;
- validation result;
- quote revision;
- correlation ID;
- and external reference.
24. Illegal Transition
Illegal transition should produce:
- stable reason code;
- current state;
- allowed actions;
- and conflict information.
Avoid generic HTTP 400 without domain meaning.
25. Idempotent Transition
A command should often be idempotent.
Example:
Repeated AcceptQuote with same idempotency key should not:
- create multiple acceptance records;
- publish duplicate business effects;
- or create multiple orders.
26. Duplicate Command Semantics
Possible responses:
- return original result;
- report already completed;
- reject conflict.
Define explicitly.
27. Optimistic Concurrency
Use version check:
Expected Revision = 7
Current Revision = 8
Reject stale command with actionable conflict.
28. Pessimistic Locking
May be useful for short critical operations.
Risk:
- long user sessions;
- lock leaks;
- poor scalability.
Enterprise quote editing often needs optimistic concurrency.
29. Compare-and-Set Transition
A state transition can be executed conditionally:
UPDATE quote
SET state = 'ACCEPTED'
WHERE id = ?
AND state = 'PRESENTED'
AND revision = ?
Still validate domain guards in application/domain layer.
30. Transition Atomicity
Local transition should atomically persist:
- state;
- audit;
- and outgoing event intent where possible.
Outbox pattern can preserve event publication reliability.
31. State and Event Consistency
If state changes but event is lost:
- downstream misses fact.
If event publishes before state commits:
- consumer observes fact that may rollback.
Use transactional outbox or equivalent pattern.
32. Time Concepts
Different time semantics:
- created time;
- updated time;
- effective time;
- validity time;
- processing time;
- event time;
- received time;
- billing start;
- requested completion.
Name explicitly.
33. Effective Time versus Processing Time
Effective time
When business fact is considered true.
Processing time
When system recorded or processed it.
Example:
Customer acceptance effective at 10:00.
System receives callback at 10:05.
Both timestamps matter.
34. Event Time versus Ingestion Time
For asynchronous events:
- event occurred at;
- event published at;
- event received at;
- event processed at.
This supports latency and ordering analysis.
35. Timezone Semantics
Use:
- UTC for machine timestamps;
- explicit timezone for business deadlines;
- and local display conversion.
Quote expiry at 23:59 is meaningless without timezone.
36. Inclusive versus Exclusive Boundaries
Define whether validity interval is:
[start, end)
or another convention.
Ambiguity causes expiry bugs.
37. Date versus Instant
A business date:
2026-07-10
is not the same as an instant.
Do not convert date-only fields to midnight UTC blindly.
38. Duration versus Deadline
Duration
24 hours from event.
Deadline
End of business day in specific locale.
They are not interchangeable.
39. Quote Validity
Quote validity may depend on:
- presented time;
- generated document time;
- approval time;
- catalog/price validity;
- and customer agreement.
Define exact rule.
40. Price Validity
Price validity can be:
- rule validity;
- calculation validity;
- quote validity.
A price definition may remain valid while calculated quote becomes stale due to customer context change.
41. Approval Validity
Approval may expire when:
- time passes;
- price changes;
- margin changes;
- quantity changes;
- terms change;
- or approver authority ends.
Define invalidation triggers.
42. Catalog Effective Dating
Catalog entity may be:
- published now;
- effective later;
- retired later.
Quote may be created before effective date but accepted after.
Policy must be explicit.
43. Requested Date versus Committed Date
Requested
Customer preference.
Committed
Provider promise.
Actual
Observed completion.
Do not store all as one field.
44. Timeout
A timeout means no result arrived within expected duration.
It does not necessarily mean operation failed.
This creates ambiguous outcome.
45. Ambiguous Success
Example:
- Order Service accepts request.
- Response is lost.
- Caller times out.
- Caller retries.
Without idempotency, duplicate order may be created.
46. Retry State
Retries should track:
- attempt;
- next retry;
- last error;
- classification;
- and maximum policy.
Avoid hiding retry as generic PROCESSING.
47. Backoff
Use:
- fixed;
- exponential;
- jitter;
- or policy-based backoff.
Choose based on dependency behavior.
48. Retryable versus Non-Retryable
Retryable:
- temporary network issue;
- 503;
- transient lock.
Non-retryable:
- invalid state;
- authorization failure;
- semantic rejection.
Incorrect retries amplify failures.
49. Expiry
Expiry is a business transition caused by time.
It should be:
- deterministic;
- auditable;
- idempotent;
- and observable.
50. Scheduled Transition
Options:
- scheduler;
- delayed message;
- workflow timer;
- periodic scan.
Each has trade-offs.
51. Timer Reliability
Questions:
- What if timer fires twice?
- What if scheduler is down?
- What if clock changes?
- What if entity changes before timer fires?
52. Clock Abstraction
Domain logic should use controllable clock abstraction for testing.
Avoid direct calls to system time throughout code.
53. Long-Running Process
Quote approval or order fulfillment may last:
- hours;
- days;
- months.
Do not hold database transaction or lock for lifecycle duration.
Use persisted process state.
54. Saga
Saga coordinates long-running multi-step process.
It may use:
- orchestration;
- choreography;
- compensation;
- and timeout.
Saga state must be observable.
55. Compensation
Compensation is a new action to counter prior effect.
It is not perfect rollback.
Example:
- cancel reservation;
- issue credit;
- create reverse order.
56. Irreversible Transition
Examples:
- signed contract;
- physical shipment;
- external number port;
- invoice issued.
After irreversible milestone, change requires new business process.
57. Cancellation
Cancellation should define:
- allowed states;
- scope;
- actor;
- reason;
- compensation;
- and resulting state.
58. Rejection
Rejection is not always terminal.
Possible behaviors:
- return to draft;
- create new revision;
- close quote;
- request more information.
Define explicitly.
59. Reopen
Reopen can violate history if it mutates terminal entity.
Alternative:
- create new revision;
- clone;
- amendment;
- or new quote.
60. Amend
Amendment should preserve:
- original commitment;
- delta;
- authority;
- and effective time.
Do not mutate accepted history.
61. Partial Completion
Order may complete partially.
Need:
- item-level state;
- parent aggregation;
- business rule;
- customer communication;
- and billing behavior.
62. Parent State Aggregation
Possible rule:
If all items completed -> COMPLETED
If any failed and none active -> PARTIALLY_COMPLETED
If any active -> IN_PROGRESS
The actual rule is domain-specific.
63. State Aggregation Risk
A parent COMPLETED can hide failed items if aggregation is careless.
Always preserve item-level truth.
64. Held State
HELD should explain:
- who placed hold;
- why;
- what condition releases it;
- and timeout/escalation.
Avoid permanent limbo.
65. Pending State
PENDING is too generic.
Qualify:
- PendingApproval;
- PendingCustomer;
- PendingDependency;
- PendingPayment.
66. Failed State
Failure should include:
- failure class;
- reason;
- retryability;
- owner;
- and recovery action.
67. Terminal State
A terminal state means normal lifecycle no longer progresses.
Possible terminal states:
- Completed;
- Cancelled;
- Rejected;
- Expired;
- FailedFinal.
But support actions may still occur.
68. Soft Terminal State
A soft terminal state may be reopened under special policy.
If so, document:
- authority;
- audit;
- and semantics.
69. State History
State history should record:
- previous state;
- next state;
- command;
- actor;
- time;
- reason;
- version;
- and correlation.
70. Event Sourcing
Event sourcing stores state changes as events.
Benefits:
- history;
- replay;
- audit.
Costs:
- complexity;
- schema evolution;
- projection;
- and operational learning.
Do not choose only because audit is needed.
71. Audit Log versus Event Store
Audit log
Records who changed what.
Event store
Authoritative persistence of domain events.
They are not interchangeable.
72. State Reconstruction
If state is reconstructed from events:
- ordering;
- duplicate;
- versioning;
- and missing events
must be handled.
73. Snapshot in Event-Sourced Model
Snapshot improves replay performance.
It must retain:
- event position;
- schema version;
- and validation.
74. State Machine Implementation Options
- explicit domain code;
- workflow engine;
- rules engine;
- database constraints;
- state-machine library;
- event-sourced aggregate.
Choose based on complexity and ownership.
75. Workflow Engine
Benefits:
- visual process;
- timers;
- human tasks;
- persistence.
Risks:
- business logic split;
- opaque scripts;
- vendor coupling;
- and difficult testing.
76. State-Machine Library
Benefits:
- explicit transitions;
- reusable infrastructure.
Risks:
- framework complexity;
- and domain language hidden behind generic callbacks.
77. Database State Machine
Database constraints can protect:
- uniqueness;
- valid values;
- and atomic conditions.
They should supplement, not replace, domain behavior.
78. UI-Driven State Machine Anti-Pattern
If UI buttons decide valid transition but API does not enforce it:
- automation can bypass rules;
- integrations create illegal state;
- and security depends on presentation.
79. Generic Workflow Anti-Pattern
A generic workflow table with arbitrary transitions can lose domain meaning.
Use generic infrastructure only if domain-specific guards and events remain explicit.
80. State Explosion
State explosion occurs when unrelated dimensions are combined.
Mitigation:
- separate orthogonal state machines;
- use derived views;
- model process state independently.
81. Boolean Flag Explosion
Flags:
isApproved
isSubmitted
isExpired
isCancelled
isProcessing
can produce impossible combinations.
Prefer explicit lifecycle state plus supporting facts.
82. Mutable Terminal State Anti-Pattern
Changing accepted or completed entity in place destroys evidence.
Use:
- revision;
- amendment;
- correction command;
- and audit.
83. Magic State Transition
A background job changes state with no command, reason, or event.
This breaks explainability.
84. Hidden Transition
A data update indirectly changes behavior without lifecycle event.
Example:
- setting
approved_byfield silently makes quote approved.
Avoid.
85. Transition Side Effects
A transition may trigger:
- event;
- document;
- notification;
- downstream command.
Separate core state change from unreliable external side effects.
86. Notification Failure
Failure to send email should not necessarily rollback quote acceptance.
Model notification as separate process.
87. Derived State
Some state can be derived.
Example:
IsExpired = now >= validUntil.
But persisted transition may still be needed for:
- audit;
- event;
- downstream behavior.
88. State Projection
UI may display simplified state:
Quote: Awaiting Customer
derived from:
- QuoteState = PRESENTED;
- ApprovalState = APPROVED;
- DocumentState = DELIVERED.
Projection should not become authority.
89. State Compatibility
Adding a new state can break consumers.
Need:
- tolerant consumers;
- versioning;
- mapping;
- and default behavior.
Enum evolution is high risk.
90. Unknown State Handling
External consumers should define behavior for unknown state.
Options:
- map to UNKNOWN;
- ignore unsupported transition;
- or fail visibly.
Silent incorrect mapping is dangerous.
91. Invariant Enforcement Layers
Possible layers:
- value object;
- aggregate;
- database;
- API;
- event consumer;
- reconciliation.
Critical invariants may need defense in depth.
92. Validation Timing
Validate at:
- input;
- transition;
- persistence;
- integration boundary;
- and reconciliation.
Not every validation belongs everywhere.
93. Property-Based Tests
Property-based tests can verify invariants across many inputs.
Examples:
- totals reconcile;
- invalid transitions never succeed;
- repeated idempotent command produces one effect;
- state history remains ordered.
94. Model-Based Testing
Generate command sequences from state model.
Check:
- allowed transitions;
- illegal transitions;
- terminal behavior;
- and concurrency.
95. Decision Table Testing
Useful for guards involving:
- state;
- role;
- expiry;
- approval;
- and validity.
96. Temporal Tests
Test:
- before boundary;
- exactly at boundary;
- after boundary;
- timezone change;
- daylight-saving transitions where relevant;
- delayed event;
- and duplicated timer.
97. Concurrency Tests
Test:
- two accepts;
- accept versus expire;
- revise versus approve;
- cancel versus complete;
- and duplicate conversion.
98. Recovery Tests
Test:
- event publication failure;
- timeout after downstream success;
- process restart;
- repeated callback;
- and manual repair.
99. State Metrics
Useful metrics:
- state age;
- transition latency;
- illegal-transition rate;
- retry count;
- stuck count;
- and terminal-failure rate.
100. State Age
State age answers:
How long has this entity remained here?
It is crucial for:
- pending approval;
- fulfillment;
- and recovery.
101. Stuck Detection
A process is stuck when:
- state age exceeds expectation;
- no active owner;
- no scheduled action;
- and no progress event.
102. Transition SLI
Example:
95% of accepted quotes create a product order within 2 minutes.
This connects lifecycle to reliability.
103. Manual Repair
Manual repair should use explicit commands.
Examples:
- RetryOrderConversion;
- MarkExternalCompletion;
- ReconcileInventory;
- CancelFailedItem.
Avoid direct database update.
104. Repair Preconditions
A repair command needs:
- authority;
- current state;
- evidence;
- reason;
- and idempotency.
105. Auditability
To explain any state, answer:
- What command occurred?
- Who initiated it?
- What guard passed?
- What version was current?
- What event was emitted?
- What external effect followed?
106. Defensibility
Commercial lifecycle may need legal or regulatory defensibility.
Evidence should support:
- accepted version;
- signatory;
- time;
- terms;
- approval;
- and history.
107. State Machine Review Template
## Aggregate
## States
## Commands
## Actors and Authority
## Guards
## Events
## Invariants
## Timers
## Retry and Idempotency
## Cancellation and Compensation
## Terminal States
## Manual Recovery
## Observability
108. Transition Specification Template
Name:
Current state:
Command:
Actor:
Authority:
Guard:
Atomic changes:
Event:
External effects:
Idempotency:
Failure:
Audit:
109. Temporal Policy Template
Business time:
Timezone:
Start condition:
End condition:
Inclusive/exclusive:
Expiry action:
Late-arrival policy:
Clock source:
Audit fields:
110. Worked Example: Quote Approval
States
- Draft;
- PendingApproval;
- Approved;
- Rejected.
Guard
- complete configuration;
- valid price;
- authority route exists.
Reapproval trigger
- discount changed;
- quantity changed;
- term changed;
- or revision changed.
111. Worked Example: Quote Acceptance Race
Two events occur:
- customer accepts revision 4;
- sales saves revision 5.
Need concurrency policy:
- accepted command includes expected revision 4;
- revision 5 save conflicts or creates separate draft;
- accepted revision remains immutable.
112. Worked Example: Quote Expiry Race
At 23:59:59:
- customer accepts;
- expiry timer fires.
Need:
- authoritative clock;
- atomic guard;
- and deterministic boundary rule.
113. Worked Example: Order Conversion Timeout
Quote accepted.
Conversion command sent.
Caller times out.
Retry occurs.
Need:
- conversion idempotency key;
- unique accepted-quote reference;
- original result replay;
- and reconciliation if response unknown.
114. Worked Example: Partial Order Completion
Order has three items:
- Item A completed.
- Item B completed.
- Item C failed terminally.
Possible parent state:
- PartiallyCompleted.
Need business decision:
- can customer receive partial service;
- should remaining item be amended;
- when billing starts.
115. Worked Example: Cancellation after Shipment
Customer requests cancellation after equipment shipped.
Normal rollback unavailable.
Possible compensation:
- return logistics;
- cancellation fee;
- and contract adjustment.
This is new business flow, not state reversal.
116. Worked Example: Manual Recovery
External fulfillment completed but callback lost.
Support verifies external evidence.
Repair command:
ConfirmExternalFulfillment
Guard:
- order item pending;
- external reference valid;
- authority present.
Result:
- state advances;
- audit records manual source;
- inventory sync continues.
117. Worked Example: Catalog Effective Date
Offering version 7 becomes effective Monday.
Quote created Friday using version 6.
Customer accepts Tuesday.
Policy options:
- preserve quoted version;
- require repricing;
- or disallow acceptance.
Must be explicit.
118. Senior Engineer Operating Model
Model explicitly
Use state diagrams and transition tables.
Separate concerns
Business, process, and integration state.
Define invariants
Before implementation.
Treat time as domain data
Not incidental timestamps.
Design for duplicate and delay
Assume retries and out-of-order signals.
Preserve evidence
Audit and revision identity.
Make recovery safe
Explicit commands, not database edits.
Add observability
State age and transition metrics.
119. Internal Verification Checklist
State models
- What state machines exist?
- Where are they defined?
- Are business and processing states separate?
- Are state diagrams maintained?
Transitions
- Who can trigger each transition?
- Are guards enforced server-side?
- Are reason codes stable?
- Are illegal transitions observable?
Concurrency
- Is optimistic locking used?
- What is the version field?
- How are conflicting edits handled?
- Are duplicate commands idempotent?
Time
- What timezone governs expiry?
- What is effective versus processing time?
- How are scheduled transitions executed?
- How are late events handled?
Integration
- Is outbox/inbox used?
- How are duplicate events handled?
- What ordering is assumed?
- Can events be replayed?
Recovery
- What repair commands exist?
- Can support act without database access?
- Are manual actions audited?
- How are stuck processes detected?
Testing
- Are transition tables tested?
- Are concurrency and timer races tested?
- Are property-based or model-based tests used?
- Are unknown external states handled?
120. Practical Exercises
Exercise 1 — Quote state machine
Draw states, commands, guards, and terminal outcomes.
Exercise 2 — Orthogonal state split
Take one overloaded status enum and separate business, process, and integration state.
Exercise 3 — Invariant inventory
Write 15 safety, liveness, temporal, and cross-aggregate invariants.
Exercise 4 — Race analysis
Analyze accept-versus-expire and revise-versus-approve races.
Exercise 5 — Timer policy
Design expiry with timezone, duplicate timer, and delayed processing.
Exercise 6 — Recovery command
Replace one direct database repair with an explicit audited command.
121. Part Completion Checklist
You are done if you can:
- define a state machine;
- separate business, processing, and integration state;
- write transition guards;
- distinguish safety and liveness;
- define aggregate and temporal invariants;
- model effective and processing time;
- handle expiry, retry, timeout, and ambiguous success;
- design idempotent transitions;
- preserve history and audit;
- and create safe manual recovery paths.
122. Key Takeaways
- State is behavior, not just a label.
- Business, processing, and integration states should not be conflated.
- Guards protect transitions.
- Invariants define valid domain state.
- Time is a first-class domain concern.
- Timeout does not prove failure.
- Retries require idempotency.
- Terminal history should not be mutated casually.
- Manual recovery must be explicit and audited.
- Internal state machines and temporal policies must be verified.
123. References
Conceptual baseline:
- General finite-state-machine, hierarchical-state-machine, and workflow modeling.
- Domain-Driven Design aggregates, invariants, commands, and events.
- Distributed systems concepts including idempotency, optimistic concurrency, sagas, outbox, retries, and eventual consistency.
- General CPQ, quote, approval, product-order, and fulfillment lifecycle practices.
These references do not describe internal CSG lifecycle implementation.
You just completed lesson 04 in start here. Use the series map if you want to review the broader track, or continue directly into the next lesson while the context is still warm.
Keep the momentum while the lesson is still fresh. Move backward for review or continue forward into the next concept.