jstimps

jstimps OP

DGen - A distributed GenServer

I love GenServer. There are only 2 things stopping me from writing an entire app with them:

  1. Durability: The state is lost when the process goes down.
  2. High availability: The functionality is unavailable when the process goes down.

What if we could guarantee the GenServer never went down? Could we build a stateful application without a database?


Many Erlang and Elixir developers have this fantasy at some point in their journey. But how close can we actually get to the dream? I’d like to find out with DGen. This is v0.1.0 stuff, early days.

What DGen does

DGen provides a “distributed GenServer” (DGenServer). It’s meant to work just like a GenServer, but the message queue and the module state are durably stored in FoundationDB, with other backends possible.

Quick example

Our simplest example looks almost exactly like a GenServer.

defmodule Counter do
  use DGenServer

  def start(tenant), do: DGenServer.start(__MODULE__, [], tenant: tenant)

  def increment(pid), do: DGenServer.cast(pid, :increment)
  def value(pid), do: DGenServer.call(pid, :value)

  @impl true
  def init([]), do: {:ok, 0}

  @impl true
  def handle_call(:value, _from, state), do: {:reply, state, state}

  @impl true
  def handle_cast(:increment, state), do: {:noreply, state + 1}
end

However, the state lives on beyond the lifetime of the original Elixir process.

{:ok, pid} = Counter.start(tenant)
Counter.increment(pid)
Counter.increment(pid)
2 = Counter.value(pid)

# Restart the process
Process.exit(pid, :kill)
{:ok, pid2} = Counter.start(tenant)
2 = Counter.value(pid2)  # State persisted!

The tenant argument is the only unique piece here. This tells DGenServer where to persist the queue and state in the datastore.

Beyond the basics

The simple example demonstrates the durable state. But the benefits inherited by a serializable distributed system are all here:

  • Start one DGenServer per node, with state mutations processed exactly once, without rpc coordination or process registration.
  • Separate where messages are pushed from where they are processed. Producers can run anywhere in the cluster, while consumers — the processes that mutate state — can be pinned to specific nodes or hardware.
  • Perform side effects such as sending emails or performing network requests, with similar transactional guarantees.

Embracing side effects

The simplest side effect is one that happens after a state mutation. For example, a log message is a side effect! Your callback can optionally return a function to be executed after the state change is committed.

def handle_cast(:increment, state) do
  action = &Logger.info("Counter is now #{&1}") # runs after commit
  {:noreply, state + 1, [action]}
end

On the other hand, when a side effect needs to update the state, then we must lock out the queue from processing messages while our side effect executes outside of the transaction.

def handle_cast(:send_email, state) do
  # executes inside the transaction
  {:lock, state}
end

def handle_locked(:cast, :send_email, state) do
  # executes outside of a transaction
  Req.post(...)
  {:noreply, %{state | sent: state.sent + 1}}
end

Under the hood - performance characteristics

Message Queue: The critical piece of DGenServer is the message queue. A caller must be able to push new messages onto the queue with serializability guarantees and high concurrency. This is achieved by using versionstamped keys, which exactly tie the underlying commit order with the key order.

Writes: The module state could be stored as a single term_to_binary blob. However, doing so would amplify the number of writes necessary for incremental changes. Instead, DGenServer adopts the design decisions of LiveView’s assigns and component lists. A module state consisting of a map with atom-keys or a list with string-id’d elements are optimized for incremental diffs on write. This means that standard Elixir structs are the preferred terms for the DGenServer module state.

Reads: And finally, DGenServer will cache the module state in memory to improve performance, with perfect cache invalidation. A single hot consumer will never have to read the full state, unless it restarts.

These components together allow for adequate performance. Still, you shouldn’t replace all your GenServers tomorrow. DGenServer should be reserved for stateful mutations that require durability and high availability guarantees, such that the performance tradeoff is acceptable.

Let it crash?

A DGenServer consumer can crash, just like any other Elixir process. But a key difference here is that the message queue is durable. If the crash is due to a poison message, a supervisor restart of a DGenServer consumer will simply try to process the same message again. DGen has yet to learn what this means in a production setting. Crash semantics themselves are well-defined, but system recovery is not automatic, like it is with GenServer. An operator may have to manually delete a poison message from the queue - an operation that is not possible with a standard GenServer.

Other backends?

DGen requires a strictly serializable key-value datastore with transactions, like FoundationDB, to provide the consistency guarantees to match the semantics of a GenServer. The first backend implementation available in DGen is FoundationDB, via erlfdb. But, we hope that other datastores providing a similar featureset can be implemented as alternative backends (such as Hobbes, Bedrock, etc.). I’m very open to flexing the current backend behaviour (:dgen_backend) to support other projects.

Links

https://github.com/foundationdb-beam/dgen

Community input

So I’m continuing my obsession with exploring different kinds of state engines on the BEAM. I know there are like-minded folks around, so I’d love to hear thoughts and feedback about the approach. This project isn’t meant to be integrated into your production app today, but hoping it can evolve into something useful.

First 10 of 41 Posts Switch mode

Schultzer

Schultzer

Does this have the same bottleneck issues as a GenServer does?

jstimps

jstimps OP

Yes, there is a single message queue and messages are processed in serial. There is no throughput advantage.

Werner

Werner

Speaking of “Could we build a stateful application without a database?“, there is an interesting presentation on this topic or better 2 versions of it:

dimitarvp

dimitarvp

That is so great that I’ll have a hard time not pulling away from my work to try it.

Before I get too child-like excited: are other storage backends offering less guarantees that make them bad candidates for DGen or is it simply a matter of bandwidth on your part? I’d love to explore DGen backed by Postgres (and maybe SQLite3 in the future, if it even makes the cut).

rhcarvalho

rhcarvalho

Interesting experimentation! Did you find any prior art?

I wonder if the team at Ericsson considered that when designing OTP…

jstimps

jstimps OP

Bandwidth, mainly. :smiley: I think most modern storage engines are written with serializability in mind. Shoot, you could probably do it with S3’s Strong Consistency modes. However, FDB was specifically designed for clients to implement sophisticated and language-specific data structures, so it has all the abstractions to make it convenient and fun.

I think a sqlite backend would be totally doable and successful. Obviously you lose the distributed guarantees, but you still have the durability.

For postgres, I’ve read that it takes careful precision to write a concurrency safe queue in postgres.

FDB is an ideal datastore to go zero-to-one on an experiment like this. Going from one-to-two will take a serious rethink of the backend interface. Bedrock and Hobbes are both inspired by FDB, so they are prime candidates.

Even still, how do we generalize versionstamps and watches? - an open question.

I’m hoping to keep :dgen_backend’s key-value abstractions mostly in place, and to avoid making it too SQL-y. The tradeoff of generalization is that you lose the fidelity of the best-fitting implementation.

jstimps

jstimps OP

  • ra: Raft-consensus state machine. ra is great, and provides the same basic ideas. You are responsible for forming the cluster with your BEAM nodes.
  • oban: Job processing with Postgres, MySQL, Sqlite, and others. It’s a message queue + your code. Universally loved, I hear it’s a great project.
  • Process registries such as global, Registry, and Horde
Schultzer

Schultzer

What about mnesia, I feel like that was kinda design for persistent configuration state like what we keep in a GenSever.

dimitarvp

dimitarvp

Yes, absolutely, I am with you.

I, like most commercial devs, simply have operational concerns and in this case – worries about a split-brain problem. I am desperately looking for something like Ash team’s Reactor or Flowstone that gives me an Oban-like persistent workflow orchestration with some extra bells and whistles, but that’s obviously the Y in the XY problem; persistent GenServers would do this just the same, if not better (I bet on the latter). Hence my interest in your library.

Or maybe there’s a way to embed FDB a la SQLite3? Can you give me some reading to do on what would it take to use FDB in an Erlang/Elixir project with operational concerns minimized?

And to circle back to the split-brain problem: we have a SaaS in our backend and I more or less hate it at this point – slow (45-60ms per request in prod, and we sometimes need multiple to do a full business operation), has async / eventual consistency traps, and the little value it brings is completely overshadowed by its drawbacks in general.

We need a good orchestrator before removing it though.

I’ll try DGen in the next few weeks and will let you know how it is holding up for us.

jstimps

jstimps OP

This is how I run FDB: ex_fdbmonitor | ExampleApp

It’s not an embedded database. You’re still self-hosting a service with this method, and going to production does require an operational investment in the technology, so I understand the hesitation.

Where Next? Top

Trending in Announcing Top

bluzky
You may know https://ui.shadcn.com/, a UI component library for React. I really love it’s design style and components. I’ve built some co...
387 15136 120
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
shahryarjb
The Chelekom project is a library of Phoenix and LiveView components generated via Mix tasks to fit developer needs seamlessly. One of i...
New
kip
Please say hi to a new lib, Astro that aims to deliver easy-to-consume astronomy calculations of practical use. For now it only calculat...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

Other Trending Topics Top

juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New
type1fool
I just stumbled on a newly redesigned elixir-lang.org. :tada: It looks like @Software_Mansion did the work, and I think it is generally a...
New
akoutmos
@hugobarauna and I (Alex Koutmos) have been hard at work on writing a book on Nerves that takes you from simply blinking LEDs to building...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
alexslade
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog It says that Fly is going all-in on sprites, which is a worry ...
New
matt-savvy
Is there a word for the ~> symbol used in Version strings? Do you also just call it a Squiggle Arrow™ ?!
New

We're in Beta

About us Mission Statement