Twinstate
One server truth, a live twin on every device. Declare your data once; Twinstate keeps every client's copy in step with the server — live updates, resume after a reconnect, and no lost writes when the app is killed.
Status: designed, being built. These docs describe the design; the code is being written against them, and nothing is usable yet.
Who it is for
Apps that want live, multi-device state on the storage they already have — files, a database, records kept in memory next to running processes — inside their own server, over their own socket, with no extra service. Twinstate asks only how to load and persist each record, and tracks every change itself. It does not replicate a database or bring one: where records live, how they are indexed and what goes when something is deleted stay with your store (see what your store and handlers own).
The model in one paragraph
The server owns the truth. Everything that changes it — a mutation, a client's or the server's own — runs through one queue, one turn at a time, and a record changes only through update, which records exactly which fields changed. At the end of every tick a flush sends those field-level patches, with the next revision, to every client that holds the records. Clients hold a read-only replica and render from it. Writes go into a durable outbox first, are shown immediately, and are confirmed by a reply that always arrives after the broadcast carrying their result. Nothing is ever shown that the server did not accept, except your own pending change, and only until it is confirmed.
Features
- Live on every device. A change reaches every open client in the next tick, as just the fields that changed. Nothing is wired per field, so nothing can be forgotten.
- No lost writes. Every change goes to a durable outbox first: it shows at once, survives the app being killed mid-keystroke, and is applied once, however often it is resent — the server remembers what it applied, on disk.
- Opens with data, works offline. An optional on-device cache renders the last-seen state before the socket connects, then catches up. Cached data is always corrected by the server, never trusted over it.
- Pagination built in. A collection that outgrows "every record on every device" is read through live, cursor-paged windows that stay correct as other devices change it.
- Reconnects resume. A client that drops replays only what it missed, per topic. A server restart costs one fresh snapshot.
- Typed from one declaration. The registry is the single source: store adapters, handlers, mutations, events, rejections and reads are all derived from it. Mistakes are compile or lint errors, not run-time surprises, and production spends nothing re-checking what the types proved.
- No loading waterfalls, by construction. A screen declares what it loads, and it cannot render unless something started those loads first — so a waterfall, or a read of data nobody loaded, does not compile.
- All or nothing, in memory. A change is validated, persisted, broadcast, then confirmed, in that order. A handler or validation that fails leaves nothing behind. On disk a turn is as atomic as your store: with a
transactionit is; with plain files each record is written atomically, a failed write stops the server rather than run on half-written, and the resend that follows finishes the job. - Streams text cheaply. A growing field (a streaming reply, a log) sends only its new suffix.
- Several tabs, one user. Each tab stays live on its own. Unsent work in a closed tab is picked up by another.
- Tests generated from your registry. Convergence, resends, ordering and replay are checked for every kind, mutation and entry you declare; a new one cannot escape them.
- Built for AI-written code. Every rule an agent could break is a type error or a lint error with the fix in its message — never a log line.
- Bring your own storage. Files, a database, records in memory: one small adapter per kind, and no extra service.
Optional utilities sit outside the core: device-only state and a WebSocket transport.
Getting started
sh
pnpm add twinstate zod react ws # peers: zod 4; react for twinstate/react; ws for twinstate/ws/server1. Declare your data (shared by server and client)
ts
// twin.ts — imported by both the server and the client
import { kind, ref, link, idOf, mutation, patch, registry } from 'twinstate';
import { z } from 'zod';
export const settings = kind(
'settings',
{ sort: z.enum(['recent', 'title']).default('recent') }, // a kind's fields: each a zod schema
{ load: 'instant', ops: ['update'] }, // a single value: it always exists (every field has a default), so it can only be updated
);
export const note = kind(
'note',
{ title: z.string(), updatedAt: z.string(), pinned: z.boolean() },
{ id: true, load: 'instant', ops: ['create', 'update', 'remove'] }, // ops: what any code may do to a note
);
export const noteBody = kind(
'noteBody',
{
text: z.string(), // a patch field: one writer at a time keeps every edit; two typing at once, the last wins (docs/design-notes.md)
images: ref('image').array(), // embedded records, delivered WITH the body
related: link('note').nullable(), // another root: navigate to it, never embed it
},
{ id: () => note, load: 'lazy', ops: ['create', 'update'] }, // one per note, keyed by its id; goes with its note
);
export const image = kind(
'image',
{ name: z.string(), url: z.string() },
{
id: true,
embedded: true, // delivered inside the note bodies that ref it
ops: ['create', 'remove'], // never edited (its adapter has no update); your code removes it when unused
},
);
export const twin = registry({
name: 'notes', // unique among Twinstate apps on this origin: it names everything Twinstate keeps on the device
kinds: [settings, note, noteBody, image],
mutations: {
// clients write only through what is declared here: a `patch` names the fields
// they may set; everything else (a note's `updatedAt`) only handlers change
updateSettings: patch(settings, { fields: ['sort'] }),
updateNoteBody: patch(noteBody, { fields: ['text', 'related'] }),
createNote: mutation(z.strictObject({ id: idOf(note), title: z.string() }), {
// the client chooses the id, so a resend creates nothing twice
effect: (draft, a) => {
draft.create(note, a.id, { title: a.title, updatedAt: '', pinned: false });
draft.create(noteBody, a.id, { text: '', images: [], related: null }); // so the note opens offline
},
}),
pinNote: mutation(z.strictObject({ id: idOf(note), pinned: z.boolean() })),
// the server's own writes are mutations too, which clients cannot send
touchNote: mutation(z.strictObject({ id: idOf(note) }), { from: 'server' }),
},
});2. The server
ts
import { createTwinServer } from 'twinstate/server';
import { twin, note, noteBody } from './twin'; // the kinds and registry from step 1
import { wsServerTransport } from 'twinstate/ws/server';
// `db`: any document store — get(table, id), put(table, id, doc), delete(table, id), ids(table), and
// transaction(fn). Plain files, a real database and a file journal are all in docs/transactions.md.
export const server = createTwinServer(twin, {
transaction: (run: (dbTx: DbTx) => Promise<void>) => db.transaction(run), // optional: a turn lands on disk whole
// Checked by the compiler: every kind needs exactly the adapter its declaration asks for —
// nothing missing, nothing extra (see docs/server.md). `stored` is the record as Twinstate wants
// it saved ({ value, meta }): save it as is, and give it back from `load`.
store: {
settings: {
// a single value: no id
load: () => db.get('settings', 'settings'),
update: (stored, dbTx) => dbTx.put('settings', 'settings', stored),
},
note: {
load: (id) => db.get('note', id),
list: () => db.ids('note'), // an instant kind: every note is loaded once, at startup
create: (id, stored, dbTx) => dbTx.put('note', id, stored),
update: (id, stored, dbTx) => dbTx.put('note', id, stored),
remove: async (id, dbTx) => {
// Twinstate calls only the parent's remove: its body goes with it here
await dbTx.delete('note', id);
await dbTx.delete('noteBody', id);
},
},
noteBody: {
// keyed by its note's id: loaded by that id, never listed; no remove — it goes with its note
load: (id) => db.get('noteBody', id),
create: (id, stored, dbTx) => dbTx.put('noteBody', id, stored),
update: (id, stored, dbTx) => dbTx.put('noteBody', id, stored),
},
image: {
// ops: ['create', 'remove'] — so no update
load: (id) => db.get('image', id),
create: (id, stored, dbTx) => dbTx.put('image', id, stored),
remove: (id, dbTx) => dbTx.delete('image', id),
},
twinstate: {
// Twinstate's own small records (which mutations each client had applied), kept with your data
load: (id) => db.get('twinstate', id),
save: (id, value, dbTx) => dbTx.put('twinstate', id, value),
remove: (id, dbTx) => dbTx.delete('twinstate', id),
list: () => db.ids('twinstate'),
},
},
handlers: {
// `tx` is always Twinstate's turn handle — never the database's
// updateSettings and updateNoteBody are `patch` mutations: applied for you
createNote: async ({ id, title }, tx) => {
// create-if-absent, and both commit together at the end of the turn — or neither
await tx.create(note, id, { title, updatedAt: now(), pinned: false });
await tx.create(noteBody, id, { text: '', images: [], related: null });
},
pinNote: ({ id, pinned }, tx) =>
tx.update(note, id, (n) => {
n.pinned = pinned; // Twinstate records: note / id / ['pinned']
}),
touchNote: ({ id }, tx) =>
tx.update(note, id, (n) => {
n.updatedAt = now();
}),
},
});
server.serve(wsServerTransport({ port: 8080 }));
// A change that no client asked for — a job, a webhook, a timer — is a mutation the server sends:
await server.mutate(twin.mutations.touchNote, { id: noteId });
// On SIGTERM: stop the partition, let your own async work finish, then exit (see docs/server.md)
process.on('SIGTERM', async () => {
await server.close(); // at once; whatever your work reports after this is saved for the next process
await myWork.finish(25_000); // your own async work, if any, however you track it
process.exit(0);
});Every write is a mutation, and goes through tx, the handle of the turn it belongs to, which only a handler gets. Code without a tx cannot write, so no change can be missed or slip in between two turns. Each change is validated, persisted, then broadcast, then replied to — never in any other order.
3. The client and React
tsx
import { wsClientTransport } from 'twinstate/ws/client';
import type { Id } from 'twinstate';
import { twin, note, noteBody } from './twin'; // the same file the server imports
import { createTwinClient, indexedDbCache, parseId } from 'twinstate/client';
import { createFileRoute, notFound, Link } from '@tanstack/react-router';
import { TwinProvider, entry, useShared, useMutation, useSyncStatus } from 'twinstate/react';
const client = createTwinClient(twin, {
transport: wsClientTransport('wss://notes.example/twin'),
// required: a deploy this bundle cannot talk to ('incompatible'), or a newer version open on this
// device ('outdated': this tab is now read-only). Yours to handle — Twinstate never reloads
onIncompatible: (reason) => showUpdateBanner(reason), // e.g. "A new version is available — reload"
// the outbox is written to IndexedDB, durably, and sent once written; flushed when the page is hidden
// optional: open with data, read offline — every field that may be stored on a device, confirmed by type
cache: indexedDbCache(twin, {
kinds: {
settings: ['sort'],
note: ['title', 'updatedAt', 'pinned'],
noteBody: ['text', 'images', 'related'],
image: ['name', 'url'],
},
}),
});
createRoot(el).render(
<TwinProvider client={client} outbox={(o) => <OutboxSheet {...o} />}>
{/* outbox: required — entries held for a person to decide, shown however you like; or `discard()` to drop them (docs/react.md) */}
<App />
</TwinProvider>,
);
// An entry declares what it loads, and can only be rendered from client.preload
export const NoteScreen = entry(
'noteScreen',
({ id }: { id: Id<'note'> }) => ({ body: noteBody(id) }),
function NoteScreen({ id, body }) {
const b = useShared(body); // lazy root through its handle: refs resolved, b.images are records
const [pin, { pending }] = useMutation(twin.mutations.pinNote); // shown at once, survives a kill
const { stale } = useSyncStatus(body); // true while what is shown may be out of date
/* … */
},
{ absent: <NotFound /> }, // required: the note may not exist
);
function NoteList() {
const notes = useShared((s) => s.note.sorted(byRecent)); // instant: always present, anywhere
/* … */
}
// src/routes/notes.$id.tsx — your router stays in charge of URLs; the route starts the load before render
// and renders what it returned (TanStack Router shown; React Router and routers without loaders — see docs/react.md):
export const Route = createFileRoute('/notes/$id')({
loader: ({ params }) => {
const id = parseId(note, params.id); // `note` is the kind from twin.ts: the URL string becomes an Id<'note'>, or null
if (!id) throw notFound(); // a malformed address is a 404
return client.preload(NoteScreen, { id });
},
component: () => <NoteScreen preloaded={Route.useLoaderData()} />, // typed from this route's own loader
});
// a hover warms the same load; the click that follows finds it under way
const NoteLink = ({ id }: { id: Id<'note'> }) => (
<Link to="/notes/$id" params={{ id }} onPointerEnter={() => client.preload(NoteScreen, { id })} />
);<NoteScreen /> without preloaded does not compile: an entry cannot render unless something started its loads before render — a route loader, a click, a hover, or its parent entry. With a cache, the app renders its last-seen data the moment it opens, and each cached topic it uses is resumed or reset against the server like any reconnect — cached data is corrected, never trusted. See React and the client.
Paging a long list
A kind that grows without bound is not instant: it is lazy, and read through a query — a live window of it. An activity log, say:
ts
export const activity = kind(
'activity',
{ text: z.string(), at: z.string(), archived: z.boolean() },
{
id: true,
load: 'lazy',
ops: ['create', 'update'], // entries can be archived later
query: { order: ['at desc'], filter: ['archived'] }, // so its adapter must answer a window
},
);
// its adapter answers one page: window({ order, filter, first, after })tsx
export const ActivityLog = entry(
'activityLog',
() => ({ page: activity.query({ order: 'at desc' }, { first: 50 }) }),
function ActivityLog({ page }) {
const p = useShared(page); // the window, live: items enter, leave and move as they change
return (
<>
{p.items.map((a) => (
<ActivityRow key={a.id} activity={a} />
))}
{p.hasMore && <button onClick={p.loadMore}>More</button>}
{/* the next 50, after p.endCursor */}
</>
);
},
);A child kind pages the same way, over one parent's children — a long transcript read 100 messages at a time (see concepts).
4. Tests generated from your registry
ts
import { describeTwin, testId } from 'twinstate/testing';
import { twin, note } from './twin';
describeTwin(twin, {
server: () => makeServer(memoryDb()),
fixtures: { createNote: { args: { id: testId(note, 'n1'), title: 'Plans' } }, pinNote: { … }, … }, // one per mutation, required
dataset: representativeData,
snapshotBudget: 200_000,
});
// registers every check — convergence, resends (across a restart), ordering, replay, windows, entries, the store … —
// for every kind, mutation and entry; a new mutation does not compile until it has a fixtureDocumentation
| page | read it for |
|---|---|
| Concepts | kinds (roots, children, embedded), who writes, what you own, queries, mutations, events |
| The server | the queue, a turn, flush, the ordering guarantees, async and long-running work |
| The client | the replica, the outbox, reconnects, the 24-hour hold, the persisted cache |
| React | the hooks, entry and preload, routers, and why there are no waterfalls |
| Sessions and access | who is connected, field and record policies, device data per user (designed, not built) |
| Protocol | the wire messages and the transport contract |
| Testing | the invariant suite and what each check proves |
| Device state | the optional twinstate/device utility |
| Scalability | what grows, what bites first, and what to do about it |
| Transactions | what transaction does: plain files, a database, and a file journal |
| Changing a schema | old data after a schema change: when a migration is needed, and how it runs |
| Comparison | where Twinstate fits next to Zero, PowerSync, Durable Objects, Liveblocks and TanStack |
| Design notes | what was considered and rejected, and the research behind each choice |