Reactive Cells: Long-Lived Components as Durable Actors with a Pure Core
By Sebastian Nowickistill itchy
Contents
- Introduction
- The Problem
- The Model
- A Cell
- The Step
- One Writer per Address
- A Durable Inbox
- The Step Is Atomic
- A Durable Outbox
- The Log Is the Record, and State Is a Projection
- Supervisors
- Effects That Need an Answer
- Yield, and Continue on the Reply
- Inject a Capability
- Many Cells at Once
- What Goes Away
- Adapting to the Host
- Costs and Limits
- When to Use It
- Conclusion
A design studio needs a fly-through video of a building for a client
meeting on Friday. On Monday, a designer uploads the model to an
online rendering service. Large renders need sign-off from the
studio's account manager, who approves this one on Wednesday.
A few minutes later, the rendering company deploys a new version and
the deploy fails. An engineer rolls it back within the hour. The
approval was lost in the restart, but nothing says so, and the render
keeps waiting for it.
On Thursday, the designer asks the rendering company's support why
the render hasn't started. Support finds the problem and asks the
account manager to approve it again. The render finishes overnight,
just in time, but the machine that rendered it reports back twice, and
the service handles each report as new. The studio gets two emails
saying the render is done, and the service bills it twice. Support
refunds the second charge. The service's rules were not wrong, but
the studio nearly missed its meeting, and support spent most of a day
on one job.
Strip away the details and the rendering service has a common shape.
A customer submits a job. Some jobs need a person's
approval before they start. The service hands each job to a
worker, a separate machine that does the work and reports back,
and every job has a deadline after which the service gives up on
it.
Most of the hard bugs in a component like this sit outside its
business rules. The rules are usually easy to state: when the worker
reports success, mark the job finished and tell the customer. The
hard part is everything around the rule: where the job lives while it
waits days for an approval, what happens if the service's
process dies between marking the job finished and telling the
customer, and what happens if the worker's report arrives twice, or
while a person is cancelling the job.
Each of those questions tends to get answered locally, with a lock
here, a retry loop there, and a recovery routine that runs at start-up
and tries to work out what the last process was doing. Every new rule
then has to consider every lock, retry and recovery path it might
touch. The complexity grows with the number of rules multiplied by the
number of failure modes.
The reactive cell answers those questions once, in its structure, so
that each rule can be written as plain logic. The idea isn't new. It's
assembled from the actor model, state machines, functional
programming's treatment of effects, event sourcing and the messaging
patterns of distributed systems. What I want to do here is derive
it from the problems it solves, so that it's clear why each part is
there and what it costs to leave one out.
The entities I have in mind share a few traits:
- they live far longer than a single request, often for days;
- they spend most of that time waiting on people, timers or other
systems;
- their inputs come from several sources, late, out of order and
occasionally twice;
- some of their decisions must happen exactly once, such as claiming a
resource or starting something that costs money.
The obvious first design keeps each job in the service's long-running
process. A thread holds the job's state, an in-memory timer fires its
deadline, and an open connection to the worker carries the worker's
reports. It's pleasant to write, and it works until the process
stops. At that point the timer, the connection and any decision that
wasn't written down are gone.
The usual second design moves the state into storage and updates it
from request handlers. That survives restarts, but the rules now live
inside functions that also talk to storage, read the clock and call
the network. Testing a rule needs a real or fake store and a fake
clock. Two handlers can update the same entity at once. Moving the
logic to another platform means rewriting every rule, because each one
is written against a particular store.
The cell is what's left after taking each of those problems away.
A cell is an addressable unit that owns one piece of state. It has:
- an address, such as an ID, that other components send messages
to;
- its state, which only the cell writes;
- an inbox, a durable queue of the messages addressed to it;
- a step function, which decides;
- an outbox, holding the effects it has decided on that the shell
hasn't finished carrying out.
At most one live instance of a cell runs per address at a time.
Between steps it keeps in memory only what it can rebuild from
storage, so its host may stop it, move it or evict it whenever it's
idle.
In the running example, each job is a cell. The diagram below also
shows two parts that later sections cover: wake-ups, which are
timers stored as data, and the event log, a shared, append-only
record of what happened.
The step is a pure function:
step(state, messages, environment) -> (next state, effects)
- State is everything the cell knows, as a plain value.
- Messages are the inputs taken from the inbox in this step, in the
order the inbox accepted them.
- Environment is a read-only snapshot of what the cell may observe
of the world during this step: the current time and a source of
random values, such as a seed. The shell builds it before the step.
- Effects are values that describe changes the cell wants made to
the world: send this message to that cell, call this service, publish
this event, wake me at this time.
That's a Mealy machine, a state machine whose output depends on both
its state and its input. It's also the shape of the update
function in the Elm architecture, Msg -> Model -> (Model, Cmd Msg),
which returns a new model and a command to run, and of
Erlang's gen_statem, whose callbacks return the next state together
with a list of actions, timeouts among them.
Wake-ups are effects like any other. The step returns "wake me at
14:00", and the shell keeps that wish wherever it keeps the rest of
the cell. When the time comes, the firing arrives in the inbox as a
message. After a restart, the shell reads the stored wake-ups back. A
timer stored as data lasts as long as the store does.
It's tempting to make the environment "the I/O" and hand the step a clock object and a random number
generator to call. I'd rather keep it a value. The step's result
should depend on its arguments alone, so that a test can pass a time
past the deadline and know what it'll get, and so that a step re-run
from its recorded inputs reaches the same decision. Elm goes further:
a program gets the current time through a subscription, which delivers
it to update as a message. That's purer, and it costs a
round trip for every reading. A snapshot per step is cheaper and still
deterministic, as long as whoever needs to replay a step records the
snapshot with it. Redux's rule for reducers says the same thing from
the other side: a reducer must not call impure functions such as
Date.now or Math.random.
In functional programming terms, the step is built from three small
and well-understood pieces. Reading an environment is the reader
monad, passing a state from one step to the next is the state monad,
and collecting a list of effects is the writer monad. Haskell's
libraries combine exactly those three into one type, RWS, and stacking pieces like these is
the idea behind monad transformers. The step does no
I/O. All of it lives in the shell, which acts as an
interpreter for the effects the step returns, an arrangement Bernhardt
calls functional core, imperative shell. That split between a
description of effects and a separate handler that performs them is
what underlies free monads and algebraic effect
handlers, and it's what Effect brings to
TypeScript. You don't need that vocabulary to build a cell.
It does show that each part has been studied for decades.
Two components that change the same state concurrently need locks,
version checks or merge rules, and every new rule has to consider every
interleaving. The cell sidesteps the question by giving each piece of
state exactly one writer. Any other component that wants the state to
change sends the cell a message and lets it decide.
That turns "who may change this?" into "who may send this a
message?", which is a question about routing instead of concurrency. A
decision that must happen once, such as granting a scarce resource,
belongs to the cell that owns the resource. That cell sees the
competing requests one after another and grants one.
How a platform keeps one live instance per address varies. A single
process holding an exclusive lock on its store gets it for free.
Cloudflare guarantees that each Durable Object has one active instance
at any particular time, and Orleans creates an actor's instance
when a message reaches an actor that has none in memory.
Elsewhere it has to be built, typically with a lease.
A cell that's been evicted needs somewhere for its messages to wait.
Networks also deliver late, twice or never, and the cell has to cope
with all three. The inbox does that with four rules.
- A message counts as delivered once the inbox has stored it. The
sender keeps it and tries again until then, so delivery is at least
once.
- Every message carries a stable ID, and the inbox drops IDs it has
seen. As long as the inbox remembers an ID, the step sees that
message once, so it doesn't have to be idempotent. This is the idempotent receiver of enterprise
messaging, placed in front of the step so that rules
can ignore repeats.
- The cell handles messages in the order its inbox accepted them.
That order belongs to the inbox. Two cells can see the same pair of
messages in different orders, which the section on the event log
deals with.
- A step may take several messages at once. Folding them in
acceptance order keeps the order the inbox gave them.
The alternative to rule 2 is to make every step idempotent, which puts
the burden on each new kind of message and each test. Messages already
need IDs for retries to work, so checking them once at the inbox is
the cheaper place to pay.
A crash can land between any two lines of the shell. If it lands after
the step decided but before the state was written, the decision is
lost. If it lands after the state was written but before the messages
were removed, they'll be handled again. So the shell does all of this
as one atomic write:
- remove the handled messages from the inbox;
- write the next state;
- add the effects to the outbox.
If the write fails, the messages are still in the inbox and the state
is still the old one, and the next attempt starts from there. Because
the step is pure, a retry with the same state, messages and
environment makes the same decision. A retry with a later time may
decide differently, for example by finding the job past its deadline.
That's safe, because the earlier decision was never written.
Any store will do, as long as the next state, the removal of the
handled messages and the new effects are written together or not at
all. A file replaced in one operation, an embedded database, a
relational database and a document store all qualify. The simplest
arrangement keeps the state, the outbox and a record of the handled
messages together in one record per cell, so that a store able to
write one record atomically is enough.
Some effects reach places the atomic write can't include: another
cell's storage, an external service, a shared log. If the shell sends
them before the write and the write then fails, the world has seen
the result of a decision that never happened. If it sends them after
the write and crashes, they're lost. The transactional outbox is the
standard answer: store the outgoing message as part of the same write
that updates the state.
After the write, the shell carries out each effect and removes it once
the receiver confirms it has it. A crash in between leaves the effect
in the outbox, and the shell sends it again on restart. The receiver
may then see a repeat, which its own inbox drops by ID.
An inbox on one side and an outbox on the other give an exactly-once
effect on the receiver's state, over a channel that only promises
at-least-once delivery. The same pairing works at other boundaries
too: between two cells, between the service and a worker, between a
component and a log. The service keeps each instruction it sends a
worker until the worker acknowledges it, and the worker ignores
instructions it has already seen.
The outbox also has to deal with an effect the receiver will refuse
every time, such as an event over the receiver's size limit. Retrying
it forever doesn't block anything, but hides the failure. I'd move
such an effect out of the outbox, keep it marked as refused with the
reason, and show the refusal wherever the cell's state is shown.
Refusals that can change on a later try, such as rate limits, stay in
the outbox.
A cell's state answers "what does this entity know now?". It can't
answer "what happened, and in what order?". An event log answers
that: a durable, append-only record that other components read. The
cell's state is a projection of the log, a view computed from its
events, so if a projection is lost, it can be rebuilt
from the log without losing any data. For that to hold, the cell
publishes each change it makes to the log as an effect through its
outbox, and its stored state can then be rebuilt by replaying the
log's events.
A router reads each event the log stores and puts it in the inbox
of every cell it concerns. Cells leave the reading to the router: a
cell that isn't running can't read, so something would have to wake it
anyway, and the router already knows which cells an event concerns.
Because the inboxes drop repeats, the router can safely reread events,
for example after a restart. It only has to make sure it never skips
one.
A distributed log rarely has a total order, and I think it's better to
accept that than to fake one. A producer can only say where its event
stands relative to the events it had seen, which is Lamport's
happened-before relation. So:
- each event names the events it follows, which makes the record a
causal graph;
- readers order events by those links, and break ties between
concurrent events with a deterministic rule, such as timestamp and
then ID, so every reader with the same events reaches the same
order;
- a step that depends on the log's order computes it from the events,
and treats its inbox's order as the order of arrival only.
That's the discipline behind conflict-free replicated data
types: when every reader merges the same set of events the same
way, the order in which they arrived stops mattering.
Some work can't be a short step, such as an external process that runs
for an hour. A supervisor is a cell that owns one such
process. It starts it, watches it, relays its reports as messages to
the cell that asked for it, and stops it. Erlang/OTP's supervisors,
which watch worker processes and react when they fail, are the
best-known form of this split.
The cell that asked for the work never runs the process itself. It
only receives the supervisor's reports in its inbox, like any other
message. Between those reports it's just a record in storage, so it
can wait for days without keeping anything running.
So far the effects have been fire-and-forget. Real rules often need
something back: read a file before deciding, fetch a URL, or POST some
data and act on the response. There are two ways to give a step that
data, and I think both have a place.
Say the job needs a worker, and an external scheduler hands them out.
The step returns an effect, "ask the scheduler to reserve a worker for
this job", and moves the cell into a state that says what it's waiting
for, awaiting worker. The step ends there. The shell carries out the
request and posts the response back into the cell's inbox as a
message, and the next step picks up where the last one stopped.
That's a coroutine yielding to its scheduler, and it's how algebraic
effect handlers work: the computation performs an operation, and the
handler decides what to do with the rest of the computation, its
continuation. The difference is that a cell's continuation
lives in storage, written down as the state awaiting worker, which is
what lets it survive a crash. Elm handles HTTP the same way: the
request is a command, and its result eventually arrives in update as
a message.
Writing the wait down as state has consequences I'd count as benefits.
The wait is visible, so anyone looking at the job can see it's waiting
for a worker. A timeout is a wake-up returned alongside the request. A
cancellation that arrives during the wait is an ordinary message the
step can handle in the awaiting worker state. A chain of such
requests, each with a compensating step for when a later one fails, is
a saga.
For a request that changes something outside the cell and isn't safe
to repeat, such as charging the customer for the job, the cell records the request under a
stable ID before the shell sends it, and the shell records the result
when it returns. After a crash, the shell finds the request:
- with a result: it passes the stored result back and leaves the
request alone;
- without a result: the outcome is unknown. A request that's safe to
repeat goes out again. Anything else comes back to the cell as an
"outcome unknown" message, which the step handles like any other
input.
Durable execution engines package this approach. Temporal stores the
results of a workflow's calls in its event history and replays them,
which is why a workflow definition has to be deterministic.
Azure Durable Functions place the same constraint on orchestrators, to
the point of providing their own current time in place of the system
clock.
The other way is to hand the step a capability, such as
readFile(path) or fetch(url), through its environment. The step
calls it and continues straight away. This is dependency injection.
Effect's type, Effect<Success, Error, Requirements>, is a well-typed
version of it: an effect lists the services it requires, and the
program supplies them. Effect even treats Clock and Random as
default services of this kind.
Injection keeps the step testable, but it gives up two other
properties. Once the step calls a capability, its result depends on
what the world returned at that moment, so a re-run after a crash may
decide differently. A slow or failing call also holds the step, and
the cell's atomic write, open for as long as it takes.
I choose between the two by looking at the data being read:
- Inject reads that behave like values: content that stays the same
once written (a file named by its hash, a versioned configuration),
that's fast to read, and whose failure should fail the whole step so
it's retried. If replay matters, record what was read along with the
step, as a durable execution engine records results in its history.
- Yield for anything slow, anything that can fail in a way the rule
cares about, anything that changes over time, and every write.
So an effect fits anything the cell has to wait for durably, inside
the system or outside it. The clock and the random source sit at the other end of that
range: they're cheap and well-behaved enough to arrive as values in the
environment.
A system rarely has one cell. It has thousands: one per job, per
order, per conversation. It helps to stop thinking of them as objects
calling each other and to treat them as data.
The set of cells is a collection of independent records. Each round of
work takes the cells whose inboxes hold messages and maps the step over
them. Each cell owns its state and only its state, so no step touches
another cell's state, and the steps can run in parallel without
locks. The shell can load all
their states in one read and write all their results in one batch.
Data-oriented design treats the data as the primary detail of a
program, drawing on database design and functional
programming, and this is that habit applied to entities: many
records of one shape, transformed together. It also fits the other
meaning of data-oriented programming, which separates code from data,
represents data with generic structures and avoids mutating it.
The contrast is with a central coordinator that reaches into many
entities' state to change them, takes locks to stay safe, and
serialises on those locks under load. A cell changes only its own
state. To affect another, it sends a message and carries on.
The same view pays off on the way out. A step doesn't send anything.
It returns its effects as data, and the shell stores them in the
outbox. By the end of a round, the shell holds every effect the round
produced before it has carried out any of them, so it can choose how
to carry them out. It can group them by receiver and send each
receiver one request instead of one per effect: one append to the
event log for the whole round, one message per worker however many
jobs it runs, one write per cell's inbox. Graphics APIs work the same
way. Vulkan has a program record commands into a command buffer and
submit the buffer to the GPU later, and its specification advises
batching work into as few submissions as possible, because each
submission carries a high overhead.
Two rules keep this safe. Effects bound for the same receiver keep the
order the steps produced them in, and each effect keeps its own ID, so
the receiver's inbox still drops repeats if a batch is sent twice.
Neither rule touches the step. The same step works whether the shell
sends its effects one at a time or a thousand at once, and the
batching strategy can change without changing a single rule.
This is the part I care most about. A cell has more named parts than a
handler that updates a record, but each part removes a class of bugs
from every rule written afterwards. A rule written as a step
only has to be right about its state, its messages and its
environment.
| Class of error | What prevents it |
|---|
| Lost updates from concurrent writers | one writer per address, one live instance |
| A decision lost between deciding and writing | state, inbox removal and outbox are one atomic write |
| A message handled twice after a retry | the inbox drops IDs it has accepted |
| A message lost in a crash | the sender keeps it until the inbox has stored it |
| An effect sent for a rolled-back decision, or lost after a committed one | the outbox is written with the state and sent afterwards |
| A timer lost on restart | wake-ups are effects stored with the cell |
| A request in flight forgotten on restart | the wait is a state, and the request sits in the outbox |
| A charge sent twice after a crash | the request is recorded first, and an unknown outcome reaches the step as an input instead of being retried blindly |
| Tests that depend on the clock or a database | the step is a function of values |
| Recovery code that only runs after a crash | restarting means handling the next message from the stored state |
Candea and Fox describe crash-only
software as having exactly one way to stop, by crashing, and one way
to start, by recovering. A cell has that property,
because it has no other way to start. After a restart, the shell reads the state, finds the
messages still in the inbox and the effects still in the outbox, and
carries on. There's a single path, so the recovery path runs every
time a cell is loaded.
The cell leaves some difficulties in place:
- Order across cells. Two cells can handle the same pair of events
in different orders. Their states agree only where their steps
compute order from the events themselves.
- External services that can't spot a repeat. The outbox delivers
at least once. If the receiver lacks a way to recognise a repeat,
such as an idempotency key, recording intent narrows the problem down
to an unknown outcome. It can't close it.
- Changing the shape of stored data. States, messages and effects
sit in storage, sometimes for months. Changing their shape means
migrating them or teaching the step to read the old shape.
The step is unaware of storage, clocks and platforms. The shell
reaches the outside through a small set of ports, and each way of
deploying the cells picks an implementation per port.
| Port | Single process | Distributed host |
|---|
| Cell storage | a local file or embedded database | each cell's own storage, or a shared database |
| Dispatch to an address | a lookup in one process, kept single by a lock on its store | the host's addressable object per ID |
| Wake-ups | a stored list and one loop | one stored alarm per cell, set to the earliest wake-up |
| Supervised process | a thread owning a child process | an object that starts a container |
| Environment | read from the machine before each step | read from the host before each step |
Because a cell keeps only rebuildable data in memory between steps, a
host that evicts idle objects can scale the system to zero, and an
entity that waits for a week costs one stored record for that week.
Some hosts allow one alarm per object; Durable Objects schedule a
single alarm at a time. A cell with several wake-ups then keeps
them in its state and sets the alarm to the earliest, which is easy
because wake-ups were data all along.
- More types. Every input is a message type, every change to the
world an effect type, and every rule a case in a step. For an entity
with three states that never waits, that's more code than the problem
needs.
- Indirection when debugging. A change of state stops being a call
stack. Following it means following a message through an inbox, a
step and an outbox, so logging and tracing have to be designed for it,
ideally with each message's ID carried through.
- Seen IDs pile up. The inbox keeps each accepted ID for as long as
a repeat might arrive. Pruning needs a bound on how late a repeat can
come, and some sources can't give one.
- Atomicity stops at the cell. One atomic write covers one cell's
step. If every cell shares one database, the shell can also deliver
messages to other inboxes in the same write. That's convenient, but
rules can quietly come to depend on it. Moving to per-cell storage
then means routing those messages through the outbox and checking
each rule that relied on the shortcut. Helland's position paper
argues, as I read it, for exactly this boundary: each entity is the
scope of its own transactions, and messages between entities arrive
at least once, so receivers have to tolerate repeats.
- One hot entity has a ceiling. One live instance handles one inbox
in order. Batching raises the ceiling, and past that point the entity
has to be split into cells that each own part of the state.
The design pays off when most of these hold:
- entities outlive a request by a long way and spend most of that time
waiting;
- inputs arrive from several sources, out of order, and sometimes twice;
- a crash, redeploy or lost connection must keep every input, and some
decisions must happen exactly once per entity;
- the same logic has to run in more than one place, or cost only its
storage while idle;
- the rules are intricate enough that you want to test them as plain
functions, or check them against a formal model;
- there are many entities with a little work each, rather than a few
under heavy load.
Workflow and job systems, order and payment lifecycles, provisioning of
long-lived resources, chat and collaboration spaces, and supervisors of
long-running processes all have this shape.
I'd reach for something else when:
- the data is plain records without a lifecycle, where rows and
handlers are simpler;
- millions of events need the same stateless treatment, where a stream
processor is cheaper per event;
- a rule needs two entities to change atomically, which usually means
they're one entity, or that the rule needs a coordinating cell and a
saga;
- the work finishes inside one request;
- the team won't keep the step pure. Once a step quietly reads the
clock or writes to storage, the replay and testing guarantees are
gone while the extra types remain, so I'd enforce purity with a test
or skip the design.
What I find appealing about the reactive cell is that it moves the
difficult questions out of the rules. Concurrency becomes routing.
Crash recovery becomes the normal path. Time becomes data. Talking to
the outside world becomes a pair of messages with a wait written down
in between. Each of those is decided once, in the shell, and every rule
written afterwards inherits the decision.
Each part is well established. What the combination adds is that the
parts cover each other's gaps. The inbox makes the step safe to retry,
the pure step makes a retry reach the same decision, the outbox makes
its effects safe to send after the fact, and storing all three makes
each of them survive a restart. Together they give a component whose
rules can be read, tested and moved to a new host as plain functions,
and I find that a lot easier to live with than the locks, retry loops
and recovery routines it replaces.