Scratch Space

Reactive Cells: Long-Lived Components as Durable Actors with a Pure Core

By Sebastian Nowickistill itchy
Contents
  1. Introduction
  2. The Problem
  3. The Model
    1. A Cell
    2. The Step
    3. One Writer per Address
    4. A Durable Inbox
    5. The Step Is Atomic
    6. A Durable Outbox
    7. The Log Is the Record, and State Is a Projection
    8. Supervisors
  4. Effects That Need an Answer
    1. Yield, and Continue on the Reply
    2. Inject a Capability
  5. Many Cells at Once
  6. What Goes Away
  7. Adapting to the Host
  8. Costs and Limits
  9. When to Use It
  10. Conclusion

Introduction

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,1 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 Problem

The entities I have in mind share a few traits:

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.

The Model

A Cell

A cell is an addressable unit that owns one piece of state. It has:

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.

Cell: one live instance per addresssend a messagenext batch, in the orderacceptedcurrent statenext stateeffectsshell carries them outresults and replies come backas messagesInboxdurable, drops repeated IDsSteppure: state, messages,environment→ next state, effectsStatewritten only by this cellOutboxeffects not yet carried outOther cells, people, theevent logOther cells, externalservices, wake-ups, theevent log

The Step

The step is a pure function:

step(state, messages, environment) -> (next state, effects)

That's a Mealy machine, a state machine whose output depends on both its state and its input.2 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,3 and of Erlang's gen_statem, whose callbacks return the next state together with a list of actions, timeouts among them.4

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.5 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.6

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,7 and stacking pieces like these is the idea behind monad transformers.8 The step does no I/O.9 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.10 That split between a description of effects and a separate handler that performs them is what underlies free monads11 and algebraic effect handlers,12 and it's what Effect brings to TypeScript.13 You don't need that vocabulary to build a cell. It does show that each part has been studied for decades.

One Writer per Address

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,14 and Orleans creates an actor's instance when a message reaches an actor that has none in memory.15 Elsewhere it has to be built, typically with a lease.

A Durable Inbox

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.

  1. 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.
  2. 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,16 placed in front of the step so that rules can ignore repeats.
  3. 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.
  4. 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.

The Step Is Atomic

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:

  1. remove the handled messages from the inbox;
  2. write the next state;
  3. 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.

message with a stable IDread statetake messages, in the order acceptedstate, messages, environmentnext state, effectsone atomic write: state, inbox removal, outboxcarry out each outbox effectconfirmedremove the effect from the outboxa seen ID is dropped hereSenderInboxShellStepCell's storageOutside the cellSenderInboxShellStepCell's storageOutside the cell

A Durable Outbox

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.17

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.

The Log Is the Record, and State Is a Projection

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,18 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.19 So:

That's the discipline behind conflict-free replicated data types:20 when every reader merges the same set of events the same way, the order in which they arrived stops mattering.

Supervisors

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.21

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.

Effects That Need an Answer

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.

Yield, and Continue on the Reply

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.

effect reserve a worker for job 42, reply as reservedeffect wake at 14:05reserve a workerworker 7 reservedmessage reserved in the inboxstate is awaiting workernext step sends the job to worker 7CellShellWorker schedulerCellShellWorker scheduler

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.12 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.3

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.22

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:

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.23 Azure Durable Functions place the same constraint on orchestrators, to the point of providing their own current time in place of the system clock.24

Inject a Capability

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.13

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:

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.

Many Cells at Once

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.

cells with mailInboxes with messagesLoad their states in onereadMap the step over them, inparallelWrite next states, inboxremovals and outboxes inone batchCarry out effects, and postreplies as messages

Data-oriented design treats the data as the primary detail of a program, drawing on database design and functional programming,25 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.26 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.27

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.

What Goes Away

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 errorWhat prevents it
Lost updates from concurrent writersone writer per address, one live instance
A decision lost between deciding and writingstate, inbox removal and outbox are one atomic write
A message handled twice after a retrythe inbox drops IDs it has accepted
A message lost in a crashthe sender keeps it until the inbox has stored it
An effect sent for a rolled-back decision, or lost after a committed onethe outbox is written with the state and sent afterwards
A timer lost on restartwake-ups are effects stored with the cell
A request in flight forgotten on restartthe wait is a state, and the request sits in the outbox
A charge sent twice after a crashthe 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 databasethe step is a function of values
Recovery code that only runs after a crashrestarting 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.28 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:

Adapting to the Host

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.

PortSingle processDistributed host
Cell storagea local file or embedded databaseeach cell's own storage, or a shared database
Dispatch to an addressa lookup in one process, kept single by a lock on its storethe host's addressable object per ID
Wake-upsa stored list and one loopone stored alarm per cell, set to the earliest wake-up
Supervised processa thread owning a child processan object that starts a container
Environmentread from the machine before each stepread from the host before each step
Steps: the same codeeverywhereSingle-process shellDistributed shellA laptop or one serverA host that evicts idleobjects

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.14 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.

Costs and Limits

When to Use It

The design pays off when most of these hold:

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:

Conclusion

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.


  1. C. Hewitt, P. Bishop and R. Steiger, "A Universal Modular ACTOR Formalism for Artificial Intelligence", IJCAI 1973, pp. 235–245, https://ijcai.org/proceedings/1973/31. ↩︎

  2. G. H. Mealy, "A Method for Synthesizing Sequential Circuits", Bell System Technical Journal 34(5), 1955, pp. 1045–1079, https://doi.org/10.1002/j.1538-7305.1955.tb03788.x. For the definition, see NIST, "Mealy machine", https://xlinux.nist.gov/dads/HTML/mealyMachine.html. ↩︎

  3. "HTTP", An Introduction to Elm, https://guide.elm-lang.org/effects/http.html. ↩︎ ↩︎

  4. Erlang/OTP, gen_statem, https://www.erlang.org/doc/apps/stdlib/gen_statem.html. ↩︎

  5. "Time", An Introduction to Elm, https://guide.elm-lang.org/effects/time.html. ↩︎

  6. Redux, "Style Guide", https://redux.js.org/style-guide, and "Prerequisite Reducer Concepts", https://redux.js.org/usage/structuring-reducers/prerequisite-concepts. ↩︎

  7. Control.Monad.Trans.RWS, the transformers package, https://hackage.haskell.org/package/transformers/docs/Control-Monad-Trans-RWS.html; Control.Monad.RWS, the mtl package, https://hackage.haskell.org/package/mtl/docs/Control-Monad-RWS.html. ↩︎

  8. S. Liang, P. Hudak and M. Jones, "Monad Transformers and Modular Interpreters", POPL '95, 1995, pp. 333–343, https://doi.org/10.1145/199448.199528. ↩︎

  9. E. Moggi, "Notions of Computation and Monads", Information and Computation 93(1), 1991, pp. 55–92, https://doi.org/10.1016/0890-5401(91)90052-4. ↩︎

  10. G. Bernhardt, "Functional Core, Imperative Shell", Destroy All Software, https://www.destroyallsoftware.com/screencasts/catalog/functional-core-imperative-shell; see also his talk "Boundaries", SCNA 2012, https://www.destroyallsoftware.com/talks/boundaries. ↩︎

  11. W. Swierstra, "Data Types à la Carte", Journal of Functional Programming 18(4), 2008, pp. 423–436, https://doi.org/10.1017/S0956796808006758. ↩︎

  12. G. Plotkin and M. Pretnar, "Handling Algebraic Effects", 2013, https://arxiv.org/abs/1312.1399, which extends their "Handlers of Algebraic Effects", ESOP 2009. ↩︎ ↩︎

  13. Effect, "Default Services", https://effect.website/docs/requirements-management/default-services/. ↩︎ ↩︎

  14. Cloudflare, "In-memory state in a Durable Object", https://developers.cloudflare.com/durable-objects/reference/in-memory-state/; "Alarms", https://developers.cloudflare.com/durable-objects/api/alarms/. ↩︎ ↩︎

  15. P. Bernstein, S. Bykov, A. Geller, G. Kliot and J. Thelin, "Orleans: Distributed Virtual Actors for Programmability and Scalability", Microsoft Research MSR-TR-2014-41, 2014, https://www.microsoft.com/en-us/research/publication/orleans-distributed-virtual-actors-for-programmability-and-scalability/. ↩︎

  16. G. Hohpe and B. Woolf, "Idempotent Receiver", Enterprise Integration Patterns, https://www.enterpriseintegrationpatterns.com/patterns/messaging/IdempotentReceiver.html; C. Richardson, "Pattern: Idempotent Consumer", https://microservices.io/patterns/communication-style/idempotent-consumer.html. ↩︎

  17. C. Richardson, "Pattern: Transactional outbox", https://microservices.io/patterns/data/transactional-outbox.html. ↩︎

  18. M. Fowler, "Event Sourcing", 2005, https://martinfowler.com/eaaDev/EventSourcing.html. ↩︎

  19. L. Lamport, "Time, Clocks, and the Ordering of Events in a Distributed System", Communications of the ACM 21(7), 1978, https://www.microsoft.com/en-us/research/publication/time-clocks-ordering-events-distributed-system/. ↩︎

  20. M. Shapiro, N. Preguiça, C. Baquero and M. Zawirski, "Conflict-Free Replicated Data Types", SSS 2011, LNCS 6976, pp. 386–400, https://doi.org/10.1007/978-3-642-24550-3_29. ↩︎

  21. J. Armstrong, Making Reliable Distributed Systems in the Presence of Software Errors, PhD thesis, KTH, 2003. ↩︎

  22. H. Garcia-Molina and K. Salem, "Sagas", SIGMOD 1987, pp. 249–259, https://doi.org/10.1145/38713.38742. ↩︎

  23. Temporal, "Workflow Definition", https://docs.temporal.io/workflow-definition. ↩︎

  24. Microsoft, "Orchestrator code constraints", https://learn.microsoft.com/en-us/azure/durable-task/common/durable-task-code-constraints. ↩︎

  25. R. Fabian, Data-Oriented Design, 2018, https://www.dataorienteddesign.com/dodbook/. See also M. Acton, "Data-Oriented Design and C++", CppCon 2014, https://isocpp.org/blog/2015/01/cppcon-2014-data-oriented-design-and-c-mike-acton. ↩︎

  26. Y. Sharvit, Data-Oriented Programming: Reduce Software Complexity, Manning, 2022, https://www.manning.com/books/data-oriented-programming. ↩︎

  27. The Khronos Group, Vulkan Specification, "Command Buffers", https://docs.vulkan.org/spec/latest/chapters/cmdbuffers.html. ↩︎

  28. G. Candea and A. Fox, "Crash-Only Software", HotOS IX, 2003, https://www.usenix.org/legacy/events/hotos03/tech/full_papers/candea/candea_html/. ↩︎

  29. P. Helland, "Life beyond Distributed Transactions: an Apostate's Opinion", CIDR 2007, https://ics.uci.edu/~cs223/papers/cidr07p15. ↩︎