Express yourself with

a finite-state machine in Scala

Michał Tomański

Overview

  • Problem(s)

  • FSM as a solution
  • Akka
  • Akka Persistent FSM
  • Demo time
  • Summary
  • Questions

Problem(s)

E.g. new user registration, buying stuff

How to model a process that:

  • has many steps, or

  • lasts some time, or

  • is not just a trivial sequence of steps

Finite-state machine

Seen by mathematicians

Actor

  • Encapsulates state and behavior
  • Reacts to a message
  • Location transparency
  • Supervision
  • High level of abstraction of concurrency

Persistent Actor

  • Persist every valid event
  • Do your business logic after it's persisted
  • In case of a failure, let it fail
  • Allow actor to gracefully recover
  • To make the recovery faster, use snapshots

Finite-state machine

A very simple model of process, consisting of:

Seen in Akka-persistence FSM

  • State names
  • Context (internal data)
  • Events
  • Transitions
  • Context changes
  • Behavior during transitions
  • Timeout events
  • Initial state name and initial context

State names

Context

Events

Transitions

Context changes

Behavior during transitions

Timeout events

Initial state name and initial context

Demo time

Express Ticket Machine

  • Stationary (at the railway station)
  • Show the soonest train connections
  • Pick one
  • Reserve a seat on that connection until payment
  • Pay
  • Print the ticket

For people who are in a hurry

Summary

Why?

  • Separation of business logic from infrastructure
  • Looks like a user story
  • Easy to maintain and extend
  • A good start for Event Sourcing and CQRS
  • Cluster Sharding for multiple concurrent process instances

Express yourself with

a finite-state machine in Scala

Michał Tomański

Made with Slides.com