DriftDB: minimum viable state synchronization
• Paul Butler
Today we’re releasing an open source data backend for real-time apps, DriftDB, along with a managed instance, Jamsocket.live.
Here’s one of the demo apps, a multiplayer Voxel editor, in action:
(This demo weighs in at under 200 lines of code, including the multiplayer functionality.)
At its core, DriftDB is an atomic broadcast channel. Clients connect via WebSocket to a particular “room”, and then can send messages to everyone else connected to that room.
DriftDB can also replay past messages, which is useful for keeping state around when clients can come and go at any time.
Retention instructions are included with each message sent to the server, allowing it to emulate a key/value store or durable stream with compaction.
There are certain patterns for turning a durable stream into useful constructs for state synchronization. We provide client-side React hooks that implement a few of them.
- useSharedState is a variation of React’s useState, except that the value is synchronized across everyone in the same room. Here’s a demo that builds a useSharedState slider from scratch in four minutes.
- useSharedReducer is a variation of React’s useReducer, and provides a form of state machine synchronization.
- usePresence is a primitive for presence. You pass it an arbitrary object, and everyone in the room gets a copy the latest value of it.
The React library also includes some other goodies: a Producer for connecting to a room, a status indicator component, and a QR code component that encodes a room URL.
This is an early beta release of DriftDB. There are things it doesn’t provide yet:
- The non-Cloudflare Worker server doesn’t implement the full room API.
- The React bindings don’t expose all the knobs (e.g. debounce periods and presence timeouts are hard-coded.)
- There’s no persistence. If you find it offensive that something calls itself a DB and doesn’t offer persistence, you can pretend it stands for “data backend”.
Despite these limitations, DriftDB in its current state is a lot of fun to play with, so we wanted to share it with the world. You can visit Jamsocket.live for a free hosted instance, or host your own instance on Cloudflare using the repo.
For more like this, subscribe to our Browsertech Digest or follow @drifting_corp on Twitter.