State
sync.state is a replicated key/value store. Every node keeps a full in-memory mirror, so reads are local and synchronous; writes broadcast a delta that every other node applies to its own mirror.
Any node may read any namespace:key. A mirror applies an entry for a namespace only when it came from the namespace's owner — the node whose id is the namespace. Among accepted entries conflicts resolve last-write-wins on a logical clock (a higher version wins; on a tie, the lexicographically greater src), so every mirror converges regardless of delivery order. Refused entries are counted in droppedForeign.
Expose a read-only observable through a public addon API. This page describes the independent Sync store used by transport infrastructure.
Import
import { State, stateKey } from '@bedrock-core/sync';
import type { StateKey, StateChange, StateChangeListener, SnapshotEntry } from '@bedrock-core/sync';
Usage
sync.state.set('mycoolitems', 'spawnRate', 5);
const rate = sync.state.get('mycoolitems', 'spawnRate'); // 5
const all = sync.state.getNamespace('drav0011_economy'); // { currency: 'gold', ... }
sync.state.subscribe(({ ns, key, value, deleted }) => { /* ... */ });
sync.state.delete('mycoolitems', 'spawnRate');
Observable values
const rate = sync.state.observe<number>('mycoolitems', 'spawnRate');
rate.get();
const stop = rate.subscribe((next, previous) => { /* react to this key */ });
observe(namespace, key) returns a standard read-only observable. Missing and deleted keys read as undefined. Only changes to that key notify it; equal values do not notify, and batch() coalesces notifications. Listener failures are isolated.
Each key stores its value in one observable, alongside its replication version and deletion marker. Writes take a structured copy, so changing the caller's original object does not change the stored value. Reads, namespace views and snapshots share that stored copy; State does not freeze it. Treat read values as immutable and publish replacements with set(): in-place mutation triggers neither notification nor replication.
Key notifications use Object.is equality on the copied value. Equal primitive values do not notify; separately copied objects and collections have new identities. batch() coalesces observable notifications, not outbound state messages. Observing a missing key does not add it to snapshots. Store-wide subscriptions report every accepted write or deletion, including unchanged values.
SyncNode clears a departed or replaced instance's namespace while retaining existing observable handles. A compatible replacement's later snapshots populate those handles. Writes and snapshots follow the protocol compatibility rules; structured values require protocol 3.
API
get
get<T = unknown>(ns: string, key: StateKey<T>): NoInfer<T> | undefined
get(ns: string, key: string): unknown | undefined
Read from the local mirror. undefined when the key is absent or tombstoned.
An explicitly stored undefined also reads as undefined, but remains a live entry in namespace views and snapshots. Use delete() to create a deletion tombstone.
getNamespace
getNamespace(ns: string): Record<string, unknown>
Every live key in a namespace as a plain object. Tombstoned keys are excluded.
The outer object is new; its values are the stored references, not fresh deep copies.
namespaces
namespaces(): string[]
Every namespace currently present in the mirror, in insertion order.
set
set<T = unknown>(ns: string, key: StateKey<T>, value: NoInfer<T>): void
set(ns: string, key: string, value: unknown): void
Write a key, apply it locally, and broadcast a state-delta. Only the namespace's owner writes it: a write to another node's namespace is dropped by every mirror, this one included, and counted in droppedForeign. See ownership.
delete
delete(ns: string, key: string): void
Tombstone a key and broadcast the delta. Deletions are tombstones rather than removals so a late-arriving older write cannot resurrect a removed key.
subscribe
subscribe(listener: StateChangeListener): Unsubscribe
interface StateChange {
ns: string;
key: string;
value: unknown | undefined; // undefined when deleted
deleted: boolean;
}
Fires on every applied change, local or remote, in every namespace. Only writes that win the last-write-wins comparison are applied, so a losing delta fires nothing.
The transport carries framework state as well as addon-owned values. Filter raw subscriptions by namespace and key when implementing a protocol.
observe
observe<T = unknown>(ns: string, key: StateKey<T>): ReadonlyObservable<NoInfer<T> | undefined>
Read and subscribe to one key. Unsubscribe from the observable to release a listener; the handle continues to read that key through deletion and peer replacement.
droppedForeign
readonly droppedForeign: number
Count of writes refused because the sender did not own the namespace.
Typed keys
import { stateKey } from '@bedrock-core/sync';
const SPAWN_RATE = stateKey<number>('spawnRate');
sync.state.set('mycoolitems', SPAWN_RATE, 5); // value must be a number
const rate = sync.state.get('mycoolitems', SPAWN_RATE); // number | undefined
StateKey<T> is a branded string — a compile-time assertion only. Like any state read, the actual value comes from whichever peer wrote it last and is never validated at runtime.
Conflict resolution
Each write stamps an entry with a version from a monotonically increasing logical clock, plus the writer's id:
- Higher
verwins. - Equal
veris broken by the highersrcstring — a total, stable rule, so every mirror picks the same winner.
Receiving a delta or snapshot also advances the local clock to at least the incoming version.
Snapshots and late join
A node that starts long after everyone else still needs the current picture. Two mechanisms cover that, and they run automatically inside state.start():
node.start()
└─ state.start()
├─ requestSync() broadcast "send me your state"
└─ broadcastOwnedSnapshots() push the owned namespaces out
requestSync
requestSync(ns?: string): void
Broadcast a request for peers to send their state. With no argument every responder replies with all of its owned namespaces; pass a namespace to ask for just that one.
sync.state.requestSync(); // everything
sync.state.requestSync('drav0011_economy'); // only that namespace
Responders answer only for their own namespace, the one named by their id. A namespace with no live owner is not re-served by whoever happens to be mirroring it, so a stale mirror is never presented as authoritative.
Empty namespaces are skipped rather than answered with an empty snapshot.
broadcastOwnedSnapshots
broadcastOwnedSnapshots(): void
Push a full snapshot of every owned, non-empty namespace to everyone. Called once at start; call it again by hand only after bulk-restoring state that peers should learn about without asking.
snapshot
snapshot(ns: string): SnapshotEntry[]
interface SnapshotEntry {
k: string;
v?: unknown;
ver: number;
src: string;
del?: boolean;
}
Serialize a namespace, including tombstones — a snapshot that dropped them could resurrect deleted keys on the receiver.
The returned entries share stored value references. Use cloneData() when a caller needs a separate mutable copy.
Deltas vs. snapshots
| Delta | Snapshot | |
|---|---|---|
| Trigger | Every set / delete | Startup, or a requestSync |
| Carries | One key | A whole namespace, tombstones included |
| Addressed | Broadcast | Broadcast at startup, direct reply to a request |
| Applied | Last-write-wins per key | Last-write-wins per entry |
Ownership
A namespace has one writer: the node whose id is the namespace. Every mirror applies that rule, this node's own included, so a write to another node's namespace is dropped everywhere and counted in droppedForeign.
observe() exposes a read-only observable handle, while its object values retain State's shared-copy semantics. Addon API bindings apply their own immutable snapshot boundary.
Sender and instance fields are cooperative protocol metadata, not authenticated identities. State is an in-memory mirror, not a shared dynamic-property store. Validate values and permission-checked operations in the owning addon; expose those operations through RPC or an addon API with authorize where applicable.
Persistence is not sync's job
sync is in-memory only, and it deliberately does not touch dynamic properties — those are pack-scoped, and each addon owns its own durability.
To persist, keep the namespace in a @bedrock-core/db document: restore it on load, then save it on every change. Do both inside system.run, since dynamic properties cannot be read during early execution, and restore before subscribing, so the restore does not save straight back.
The example stores JSON-compatible values. Collections, bigint and other structured values need an explicit durable representation or codec before writing a JSON document; the wire codec is not a database storage format.
import { schema } from '@bedrock-core/db';
import { createEngineDb } from '@bedrock-core/db/minecraft';
import { system, world } from '@minecraft/server';
const NS = 'mycoolitems';
const saved = createEngineDb(NS)
.collection('state', { schema: schema<Record<string, unknown>>() })
.for(world);
system.run(() => {
for (const [key, value] of Object.entries(saved.get() ?? {})) {
sync.state.set(NS, key, value);
}
sync.state.subscribe((change) => {
if (change.ns === NS) { saved.set(sync.state.getNamespace(NS)); }
});
});
Persist durable data in an owned db document, then map the value onto an observable exported by the addon.
Lifecycle
SyncNode starts and stops State's bus handlers. state.stop() retains local entries, observable handles and application change listeners for a restart. Call the unsubscribe functions returned by subscribe() and observe().subscribe() when their owner is disposed.
forget(namespace) invalidates a departed namespace, sets retained key handles to undefined and emits deletion notifications. SyncNode invokes it when discovery retires or replaces a peer; it is not a remote deletion request.