BBackend CourseLeroy Labs
0/0
Search the course

State machines for bookings, journals & reports

Modeling lifecycles explicitly, allowed transitions, guarding them in code and DB, action endpoints, side effects per transition, and what to do with time-based transitions.

● intermediateHostel-Web-AppSperoTek (in dev)Report-Manager-2

The concept

Many entities have a lifecycle. Without explicit rules, code ends up doing booking.setStatus(CHECKED_OUT) from anywhere, including from PENDING, so state becomes nonsense.

              approve            pay/check-in        check-out
  PENDING ─────────────> APPROVED ──────────> CHECKED_IN ──────> CHECKED_OUT
     β”‚  \ reject              β”‚  \ payment deadline passed (sweeper)
     β”‚   └──> REJECTED        β”‚   └──> EXPIRED
     └──> CANCELLED (student) └──> CANCELLED

Enforce transitions in the domain

public enum BookingStatus {
    PENDING, APPROVED, REJECTED, CANCELLED, EXPIRED, CHECKED_IN, CHECKED_OUT;

    private static final Map<BookingStatus, Set<BookingStatus>> ALLOWED = Map.of(
        PENDING,    Set.of(APPROVED, REJECTED, CANCELLED),
        APPROVED,   Set.of(CHECKED_IN, CANCELLED, EXPIRED),
        CHECKED_IN, Set.of(CHECKED_OUT));

    public boolean canMoveTo(BookingStatus next) {
        return ALLOWED.getOrDefault(this, Set.of()).contains(next);
    }
}

// in the entity: no public setStatus()
public void approve(User manager, Instant paymentDeadline) {
    transition(BookingStatus.APPROVED);
    this.approvedBy = manager;
    this.paymentExpiresAt = paymentDeadline;
}
private void transition(BookingStatus next) {
    if (!status.canMoveTo(next)) throw new InvalidBookingTransitionException(status, next);  // 409
    this.status = next;
}

In your projects

Hostel-Web-Appinitial-schema.sql (documented lifecycle) Β· InvalidBookingTransitionException Β· BookingService Β· BookingExpiredSweeper

The booking lifecycle above is documented in the schema, enforced via InvalidBookingTransitionException (returning 409), and has a time-based transition (APPROVED β†’ EXPIRED) driven by the sweeper. Approving one booking bulk-rejects the other PENDING bookings for the room, which is a side effect of the transition.

SperoTek (in dev)JournalEntry: DRAFT β†’ SUBMITTED β†’ (approved) β†’ POSTED β†’ (reversed) Β· JournalController

Journal lifecycle: DRAFT β†’ SUBMITTED (for approval) β†’ POSTED, with withdraw returning SUBMITTED to DRAFT, and reverse applied to POSTED entries. There is one path to POSTED (finish()). The action endpoints /submit, /withdraw, /post and /reverse each map to exactly one transition, plus /approval-check to preview whether approval is needed. Triggers make POSTED terminal at the DB level.

Report-Manager-2/api/report-submissions/{id}/approve|reject|request-revision|reopen|resubmit Β· AmendmentWindow

Report submissions: submit β†’ approve, reject or request revision β†’ resubmit, plus reopen inside an amendment window, which has its own expiry cleaned up every 15 minutes.

Alternatives

Approach When
Enum + guarded methods (yours) Most apps
Sealed types per state (Pending, Approved records) Compile-time impossible states
Spring Statemachine Complex machines (hierarchical states, guards, persistence)
Workflow engines (Temporal, Camunda/Zeebe, AWS Step Functions) Long-running multi-step processes with timers and human tasks
DB CHECK / trigger on allowed transitions Defence in depth (SperoTek’s posted guard)
  • Optimistic locking on transitions. Two managers approving at once: @Version or a lock ensures exactly one transition wins.
  • Idempotent transitions. approve on an already-APPROVED booking can be a no-op success rather than an error, which makes client retries safe.
  • History. Store transitions (who, when, from, to, why) in an audit table.
  • Timeouts as transitions. Model expiry explicitly (EXPIRED), not as β€œPENDING and old”.

Check yourself

1. Benefit of POST /{id}/approve over PATCH {status:"APPROVED"}?
2. Invalid transition should return…