LLD Guide ยท Module 1: Foundations ยท Lesson 01.05

State Machines and Invariants: Designing an LLD Solution Before You Code

Draw the states, list the rules, then write the code. In that order.

By Cruscible Engineering ยท Published

Most failed LLD submissions don't have a bug in the code. They have a gap in the design: a transition nobody decided on.

Chapter 5 of the LLD Guide. Chapters 2, 3 and 4 covered how to make an operation safe. This one covers what each operation should do, decided before you open the editor.

1. Two questions for every problem

Almost every Cruscible LLD brief describes things that move through states: a ride, a booking, a deployment, a circuit breaker, a task. Before writing code, answer two questions:

  1. What states can each thing be in, and which moves between them are legal? That's the state machine.
  2. What must always be true, whatever happens? Those are the invariants.

The graded scenarios are, in practice, attempts to make your code take an illegal move or break an invariant: cancel a completed ride, book a seat twice, half-open a breaker that isn't open.

2. Write the state machine down

Take a ride in a cab-booking system. From the brief you might get:

Figure: A ride: REQUESTED โ†’ ACCEPTED โ†’ IN_PROGRESS โ†’ COMPLETED, cancellable until it starts. Try an illegal move.

Now every method is a question about this diagram. Can a REQUESTED ride be completed? No. Can an IN_PROGRESS ride be cancelled? The brief decides, and if it doesn't say, that's the question to settle before coding, not after the grader asks it.

3. Encode it, don't scatter it

Put the legal moves in one place instead of in ifs spread across methods:

enum RideStatus { REQUESTED, ACCEPTED, IN_PROGRESS, COMPLETED, CANCELLED }

private static final Map<RideStatus, Set<RideStatus>> NEXT = Map.of(
    RideStatus.REQUESTED,   EnumSet.of(RideStatus.ACCEPTED, RideStatus.CANCELLED),
    RideStatus.ACCEPTED,    EnumSet.of(RideStatus.IN_PROGRESS, RideStatus.CANCELLED),
    RideStatus.IN_PROGRESS, EnumSet.of(RideStatus.COMPLETED),
    RideStatus.COMPLETED,   EnumSet.noneOf(RideStatus.class),
    RideStatus.CANCELLED,   EnumSet.noneOf(RideStatus.class)
);

private void move(Ride ride, RideStatus to) {
    if (!NEXT.get(ride.status).contains(to)) {
        throw new IllegalStateException(ride.status + " -> " + to + " is not allowed");
    }
    ride.status = to;
}

Every public method becomes short: find the thing, move it, do the side effects. An illegal move fails the same way everywhere, which is what the grader checks.

๐Ÿ’ก Tip: Terminal states (COMPLETED, CANCELLED) map to an empty set. Repeating a move into a terminal state should fail just as loudly as any other illegal move, unless the brief says it's a no-op.

When the state lives in Postgres or Redis, the same table drives a conditional write. That makes each transition atomic too:

int changed = db.update(
    "UPDATE rides SET status = 'ACCEPTED', driver = ? WHERE id = ? AND status = 'REQUESTED'",
    driverId, rideId);
if (changed == 0) throw new IllegalStateException("ride " + rideId + " is not waiting for a driver");

4. Time is a state too

Some machines move on a timer, not a call. A circuit breaker goes OPEN โ†’ HALF_OPEN after a cool-down, and a reservation expires after a hold. Don't start a background thread to flip it. Compute the state when you're asked:

private State currentState(long nowMs) {
    if (state == State.OPEN && nowMs - openedAt >= coolDownMs) {
        state = State.HALF_OPEN;          // the cool-down elapsed: allow a trial call
    }
    return state;
}

This is easier to make thread-safe (do it under the same lock as the other transitions), and it can't drift from the clock.

5. List the invariants, then guard them

Invariants are the "always" sentences of the brief, plus the ones it implies:

SystemInvariants
Parking lotA spot holds at most one vehicle; a vehicle is in at most one spot; free + taken = total
Railway bookingBooked seats โ‰ค capacity; a waitlisted passenger gets a seat only when one is released, in order
Rate limiterNo more than N allowed calls in any window, under any concurrency
Task queueEach task is handed to exactly one worker; a failed task is retried or dead-lettered, never lost

For each invariant, decide what enforces it:

If you can't name the thing that enforces an invariant, the grader will find the interleaving that breaks it.

6. Decide what every method returns

From the contract, write one line per method before coding. For a made-up reservation system it might look like this:

MethodSuccessNot foundInvalid / illegal
reserve(itemId, userId)reservation idIllegalArgumentException (unknown item)null when sold out
release(reservationId)truefalseIllegalStateException when already used

Your problem's real choices come from its contract's comments and its brief. What matters is that you make them once and consistently. Mixed behaviour, null in one method and an exception in its twin, is a common way to lose scenarios.

7. A one-page design

Before coding, fill in:

  1. Entities and their states (one diagram each).
  2. Legal transitions (the NEXT table).
  3. Invariants, each with what enforces it.
  4. Return values and errors per method.
  5. Where the state lives: memory, Redis keys or Postgres tables.
  6. Concurrency hot spots: which operations can race with which.

It takes ten minutes and replaces an hour of submit, fail, guess.

Takeaways

Try it yourself: Build a Cab Booking System (a ride lifecycle), Build a Circuit Breaker (time-driven states) and Build a Deployment Pipeline Engine (stages, rollback and history).