Synced Store Limitations
This page documents important limitations and constraints when using the Synced Store API. Understanding these will help you avoid common pitfalls.
Key Constraints
Table keys must be:
- Strings - Numbers and other types will be coerced to strings
- Less than 512 KB - Keys exceeding this limit will be rejected. Note that the table name is prepended to the key internally. This combined string must stay under the 512 KB limit.
// Your code
await tx.table('tasks').set('task-123', { ... });
// Internal key becomes: "tasks/task-123"Value Constraints
All values are serialized using JSON.stringify(). They must be:
- JSON-serializable - Only valid JSON types allowed
- Less than 1 MB - Serialized values exceeding this limit will be rejected
// Wrong
await tx.table('items').set(id, {
createdAt: new Date(), // Not serializable
callback: () => {}, // Not serializable
});
// Correct
await tx.table('items').set(id, {
createdAt: Date.now(),
createdAtISO: new Date().toISOString(),
});Mutator Constraints
No Browser APIs in Mutators
Mutators execute in both the browser and on the server. They cannot access outside variables and can only use JavaScript globals available in both environments. Accessing browser globals such as navigator, document, or any user-defined global will result in unexpected behavior.
// Wrong - uses browser globals
Poe.setupStore({
mutators: {
async updateItem(tx, { id }) {
const lang = navigator.language; // Not available on server!
const item = await tx.table('items').get(id);
await tx.table('items').set(id, { ...item, lang });
}
}
});
// Correct - pass values from outside when invoking a mutator on the client
Poe.setupStore({
mutators: {
async updateItem(tx, { id, lang }) {
const item = await tx.table('items').get(id);
if (!item) {
throw new Error(`Item does not exist. (itemId: ${id})`);
}
await tx.table('items').set(id, { ...item, lang });
}
}
});
// Then call with browser value from client code
await store.mutate.updateItem({ id, lang: navigator.language });No Side Effects in Mutators
Mutators should only modify store data through the transaction API. Do not:
- Make HTTP requests
- Modify global state
- Access browser storage
All Transaction Operations Must Be Awaited
Mutator functions must be async and must await all transaction operations. Failing to await will cause data loss or inconsistent state:
// Correct - awaits the operation
async addItem(tx, { id, name }) {
await tx.table('items').set(id, { id, name });
}
// Wrong - missing await, operation may not complete
async addItem(tx, { id, name }) {
tx.table('items').set(id, { id, name }); // Missing await!
}Mutators Generally Should Be Deterministic
Mutators run on both client and server. In most cases, for best user experience mutators should produce identical results given the same inputs. Avoid randomness inside a mutator.
// Wrong - ID generated inside mutator
async addItem(tx, { name }) {
const id = crypto.randomUUID(); // Different on client vs server!
await tx.table('items').set(id, { id, name });
}
// Correct - ID generated outside mutator
const id = crypto.randomUUID();
await store.mutate.addItem({ id, name: 'Widget' });
async addItem(tx, { id, name }) {
await tx.table('items').set(id, { id, name });
}Beware of optimistic lock contention
Large aggregations should be done via a .query on the client rather than computed and written in a mutation. Any .get or .scan call implicitly includes the read value in an optimistic lock check. If the value changes in another process during the mutation, the optimistic lock check will fail and the results of the mutation will be rolled back. The client and server have built in retry logic, but if the max number of retries is exceeded, the mutation will be discarded and the store.onFailedMutation callback will be called.
// Wrong - causes lock contention on every todo change
Poe.setupStore({
mutators: {
async updateTodoCount(tx) {
let count = 0;
for await (const { value } of tx.table('todos').scan()) {
count++; // Every todo is tracked for optimistic locking
}
await tx.table('metadata').set('todoCount', { count });
}
}
});
// If any todo changes while this runs, the mutation fails and retries.
// With many todos, conflicts become frequent.
// Correct - compute aggregations on the client with query
const count = await store.query(tx => {
let total = 0;
for await (const { value } of tx.table('todos').scan()) {
total++;
}
return total;
});
// Use the count directly in your UI
console.log(`Total todos: ${count}`);Data Operations
set() Does Not Merge
The set() operation completely replaces the value at a key. It does not merge with existing data:
// Initial data
await tx.table('users').set('user-1', {
name: 'John',
email: '[email protected]',
role: 'admin'
});
// This OVERWRITES - email and role are lost!
await tx.table('users').set('user-1', { name: 'Jane' });
// Result: { name: 'Jane' } - other fields gone
// Correct: Read first, then spread
const user = await tx.table('users').get('user-1');
if (!user) {
throw new Error(`User does not exist. (userId: user-1)`);
}
await tx.table('users').set('user-1', { ...user, name: 'Jane' });
// Result: { name: 'Jane', email: '[email protected]', role: 'admin' }No Partial Updates
There is no built-in way to update specific fields. You must always:
- Read the existing value
- Merge with your changes
- Write the complete new value
Store Configuration Script
Must Use Specific Script Tag
The store configuration must be in a script tag with id="poe-store-config":
<!-- Correct -->
<script id="poe-store-config">
Poe.setupStore({ mutators: { ... } });
</script>
<!-- Wrong - missing or wrong id -->
<script>
Poe.setupStore({ mutators: { ... } });
</script>Performance Considerations
Why Mutations Might Fail
Optimistic Lock Conflicts
The Synced Store uses optimistic locking to handle concurrent modifications safely. Here's how optimistic locking works:
Which keys are tracked for locking:
- Keys that are read via
get()are tracked - Keys that are checked via
has()are tracked - Keys that are only written via
set()ordelete()(without aget()orhas()) are not tracked
When a mutation executes, the system records the version of each key that was read. At commit time, if any of those keys have been modified by another client since they were read, the mutation fails with an optimistic_lock_conflict error. Both the client and server have built in automatic retry logic. If all retries fail the mutation will be reverted and the store.onFailedMutation callback will back triggered.
// This mutation WILL cause conflicts under concurrency
// because it reads before writing
async increment(tx, { key }) {
const current = await tx.table('counters').get(key) || 0; // Read → tracked
await tx.table('counters').set(key, current + 1); // Write
}
// This mutation will NOT cause conflicts
// because it only writes (no reads)
async setDirectly(tx, { key, value }) {
await tx.table('data').set(key, value); // Only write → not tracked
}When conflicts occur:
If two clients both try to increment the same counter simultaneously:
- Both read the current value (e.g.,
5) and its version (e.g.,v10) - Both compute the new value (
6) - One commits first, updating the key to version
v11 - The second tries to commit, but the key is now at
v11, notv10 - The second mutation fails with
optimistic_lock_conflict
Execution Errors
If a mutation fails during the client (optimistic) run of the mutation, an error will be thrown to the caller of the mutation. If there is an execution error on the server, the mutation will be discarded and the store.onFailedMutation callback will be invoked on the client.
async updateItem(tx, { id, name }) {
const item = await tx.table('items').get(id);
if (!item) {
throw new Error(`Item does not exist. (itemId: ${id})`);
}
await tx.table('items').set(id, { ...item, name });
}Error Handling
Errors in Mutators
If a mutator throws an error, the mutation is not applied. Always validate before writing:
async updateItem(tx, { id, name }) {
const item = await tx.table('items').get(id);
if (!item) {
throw new Error(`Item does not exist. (itemId: ${id})`);
}
if (!name || name.trim() === '') {
throw new Error('Name cannot be empty.');
}
await tx.table('items').set(id, { ...item, name: name.trim() });
}See Also
- Synced Store API - Complete API reference
- Poe Embed API - Core Canvas app API
- Canvas Apps Overview - Getting started with Canvas apps