liveBook · Manning

Finite-state machine

As explained in Build and Orchestrator in Go (From Scratch)

A state machine is a computational model consisting of defined states and transitions between those states in response to events or conditions.

A finite-state machine makes a task’s lifecycle explicit. It represents the states a task can occupy and the events that permit movement between them, preventing invalid transitions in an orchestration worker. section 4.0 section 4.6.3

Start with a small set of named states: Pending, Scheduled, Running, Completed, and Failed. A transition table records the current state, triggering event, and resulting state; each row is a permitted operation. section 4.6.3 section 4.6.3

Implement the machine with explicit transition data and a small validation interface:

  • Map each current state to its valid destination states. section 4.6.3
  • Use a containment helper to test whether a destination appears in the allowed slice. section 4.6.3
  • Expose ValidStateTransition so callers can ask whether a task may move from one state to another. section 4.6.3
  • Keep terminal states such as Completed and Failed without outgoing transitions. section 4.6.3

Scheduling and starting a task

A Pending task can respond to a ScheduleEvent by becoming Scheduled. A Scheduled task can respond to StartTask by becoming Running, but it cannot jump directly from Running back to Scheduled. section 4.6.3

Listing 4.9 The State type, which defines the valid states for a task
const (
   Pending State = iota
   Scheduled
   Running
   Completed
   Failed
)

Inspect the minimal State definition used to name the task lifecycle states. section 4.6.3

How Build and Orchestrator in Go (From Scratch) covers it

How deep it goes
Defines states, models valid transitions, and implements lookup helpers, while stopping short of production-scale orchestration complexity.
Examples
Uses Pending, Scheduled, Running, Completed, and Failed states with scheduling, starting, and stopping events.
What it assumes
Assumes task and worker concepts while defining the states, events, and transition checks needed to implement the model.
What you can do after
Build a small task state machine and validate transitions through a map and helper functions.
How it connects
Connects task lifecycle, events, workers, and orchestration systems including Borg, Kubernetes, and Nomad.

Also explained in

Compare how 9 books explain finite-state machine →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build and Orchestrator in Go (From Scratch). The section links point to the parts of the book it draws on.