Express yourself with

a finite-state machine in Scala

Michał Tomański

mtomanski@virtuslab.com | @michaltomanski

Overview

  • Problem(s)

  • FSM as a solution
  • Short on Scala and Akka
  • A bit more about Akka Persistent FSM
  • Demo time
  • Summary
  • Questions

Who are you?

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

Scala

  • JVM
  • OOP & FP
  • strong & static typings
  • complex type system
  • awesome DSLs

Akka

  • A toolkit focused on actors model
  • For Scala and Java 
  • Useful for concurrent, distributed and message driven systems
  • High-level abstraction

Actor

  • Encapsulate state and behavior
  • React to a message
  • Location transparency
  • Supervision

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 computation, 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
  • 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

mtomanski@virtuslab.com | @michaltomanski

FSM

By Michał Tomański