Session Types And The Typestate Pattern
Thu Oct 09 2025
Distributed systems really shouldn’t be this hard! A genuine issue I have with distributed systemsDistributed systems are my primary area of inquiry and my chosen specialty. Ugh. is how hard they are to design, build, test, and operate well. Resultingly, I always try to keep my eyes open for ways to ease such challenges and smooth these obstacles. Sometimes I even find something.
Of late, I have been looking at session types as a way to simplify things.
Session types bring many benefits but one such benefit is the ability to make protocol problems into compiler errors.
Traditionally, this is done by encoding valid sessions using a language’s type system.
You can see an example of this in the session_types crate as described by the accompanying paperIf you like this sort of thing, also take a look at the sesh crate!.
Ever since reading The Typestate Pattern in Rust back in 2019, it’s been stuck in my head.
Something about the way that you can make a Finite-State Machine using only Rust structs.
It’s so cool and it’s so simple that I wondered what’s at the intersection of session types and the typestate pattern.
Is it possible to do something with both of them, together?
Assume we have a simple storefront protocol for an online e-commerce operation. It involves things like looking up orders and adding products to the cart. How could such a thing look? Further, how could such a thing be encoded using the typestate pattern?
In a world where a customer has only one global cart, let’s conceive of a cart status protocol.