Overview
Every Instance has a state property — a key-value store scoped to that instance. In single-node mode it lives in memory; with Redis it is stored in a Redis hash and consistent across all nodes.
Instance state is for runtime data: active while the instance exists, discarded when it is destroyed. It is not a database replacement.
API
| Method / Property | Description | Returns |
|---|
instance.state.get(key) | Get a value. Returns undefined if not set. | Promise<unknown> |
instance.state.set(key, value) | Set a value (JSON-serialized). | Promise<void> |
instance.state.delete(key) | Remove a key. | Promise<void> |
instance.state.keys() | List all keys in this namespace. | Promise<string[]> |
instance.state.clear() | Remove all keys in this namespace. | Promise<void> |
Examples
// Boss health
await dungeon.state.set('boss-health', 5000);
dungeon.on('attack-boss', async (session, payload) => {
const { damage } = payload as { damage: number };
const health = (await dungeon.state.get('boss-health') as number) ?? 0;
const newHealth = Math.max(0, health - damage);
await dungeon.state.set('boss-health', newHealth);
dungeon.broadcast('boss-health-updated', { health: newHealth });
if (newHealth === 0) {
dungeon.broadcast('boss-defeated', { killer: session.userId });
}
});
// Match timer
match.onJoin(async () => {
if (match.sessions.length === 2) {
await match.state.set('started-at', Date.now());
match.broadcast('match-started', { timeLimitMs: 5 * 60 * 1000 });
}
});
// Kill counter
dungeon.on('monster-killed', async (session) => {
const kills = ((await dungeon.state.get('kills') as number) ?? 0) + 1;
await dungeon.state.set('kills', kills);
dungeon.broadcast('kill-count', { kills });
});
Cleanup
domain.destroyInstance(id) automatically callsinstance.state.clear(). You can also clear manually.
// Automatic
await world.destroyInstance('dungeon-1');
// Manual reset
await dungeon.state.clear();
// Delete individual key
await dungeon.state.delete('boss-health');
Use cases
- Match timers and countdowns
- Boss / objective health and progress
- Runtime counters (kills, score)
- Active objectives or flags
- Game phase / round state
- Per-instance configuration
⚠Instance state is not persistent. With Redis, it survives node restarts but is cleared when the instance is destroyed. Use your own database for data that must outlast instances.