Debugging the DB
The db decides a lot on its own: which loader serves a query, which rows it holds, which socket topics it opens. When something looks wrong, the answer is almost always in one of those decisions, and every one of them can be read. This guide starts with the tools that show them, then walks through the problems people hit most, as symptom, cause and fix.
- How to read a query's plan with
explain(), and the whole db withinspect(). - How to watch the db in HyperFlow.
- How to catch every failure with
db.onError. - How to fix the most common compile errors.
- How to fix stale, missing, extra and flashing rows, and extra requests.
The tools
explain(): one query
db.postSummary.where((post) => and(eq(post.teamId, "t1"), gt(post.likes, 10))).explain();
| Field | Tells you |
|---|---|
kind | list, one, local, or error when no loader can serve the query |
loader | Which loader serves it, as its index in the collection's chain |
sent | The conditions sent to the backend |
local | The conditions run on the returned rows |
answeredLocally | Whether held rows answer it with no request |
syncs | The socket topics keeping it live, once the query is mounted |
error | Why the query cannot be served |
inspect() and onChange(): the whole db
const snapshot = db.inspect();
// snapshot.collections: rows, pending optimistic layers and loaded subsets (fresh, live, loading, error, observers)
// snapshot.queries: every live query with its subscribers, status and plan
// snapshot.outbox: writes waiting to be replayed
db.onChange(() => console.log(db.inspect()));
HyperFlow
Pass the db to the devtools plugin, and the DB Inspector shows the same snapshot live:
import { DevtoolsPlugin } from "@hyper-fetch/plugin-devtools";
client.addPlugin(DevtoolsPlugin({ appName: "Teamboard", dbs: [db] }));
db.onError: every failure in one place
Requests, writes and queries never throw. Everything that fails reaches one listener:
db.onError(({ type, error, collection }) => {
console.error(`[db] ${type} failed in ${collection ?? "db"}`, error);
});
Wire it to your error reporting early. A load or sync error usually means a rows or row mapping met a response
it did not expect, which stays invisible in the UI until rows go missing.
Compile errors
A query does not compile
Symptom: useLiveQuery(db.postSummary.where(...)) or .get() is a type error about the query.
Cause: no loader of the collection can serve the query. Either the query does not set a loader's required filter as
a top-level eq, or the only loader that fits is paginated and cannot send one of the query's conditions or orders.
Fix:
db.postSummary.where((post) => or(eq(post.teamId, "t1"), eq(post.teamId, "t2")));
db.postSummary.where((post) => eq(post.teamId, "t1"));
- Set the required filter with
eqat the top level, or inside a top-leveland. Insideorornotit does not count. - For a paginated loader, declare every field the query filters and sorts by, or drop that condition.
- To read only rows other queries loaded, use
.local(), which needs no loader.
createDb does not compile
Symptom: createDb({ post: Post }) is a type error, or .load() and .sync() are missing after an earlier call in
the chain.
Cause: a loader, sync, ingest, normalize or mutate produced rows that are not exactly the schema's rows, so the
chain returned a RowMismatch. Hover the collection to see received and expected.
Fix: map the rows in that step. The most common case is a socket message with fields the collection lacks:
collection(PostSummarySchema, { key: "id" })
.sync(onPostChanged, { type: "update" })
.sync(onPostChanged, { type: "update", row: ({ body, ...changes }) => changes });
The db never reads schemas at runtime, so it cannot drop body for you, and a summary must never gain a field it does
not declare.
Rows that do not update
A socket event never shows
Check, in this order:
- Is the query mounted? Syncs start with the first subscriber.
explain().syncsis empty for a query nobody subscribes to, and.local()queries never start syncs. - Does a sync cover this subset? A sync with
wherecovers only the values it maps.onPostChangedfor teamt1does not cover a query for teamt2. Compare the topic inexplain().syncswith the topic your server sends to. - Does the collection hold the row? An
updatefor a row the collection does not hold is ignored. Addincomplete: "refetch"to load such rows by key. - Did the mapping fail? A
roworkeymapping that throws is reported astype: "sync"indb.onError, and the next events still apply. - Is the socket connected? While it is not, the query reports
stale: true.
A write to post does not show in the feed
Cause: the feed reads postSummary. An optimistic change reaches another collection only through a link.
Fix: createDb(collections, { links: [["post", "postSummary"]] }). See
List and Detail Views.
The old value flashes back after a write
Cause: the response is not the updated row, or a list response sent before the write arrived after it, with no
version to order the two.
Fix:
- If the server changes more than you sent, use
onSuccess: "refetch", which keeps the change on screen until the reload lands. - If a socket event confirms every write, use
onSuccess: "sync". - Add
version: "updatedAt"to collections with syncs. Ordering by the server's version is the most robust option.
A new row is missing from a paginated list
Cause: a new row joins a paginated list only when it sorts inside the loaded pages, or anywhere once the backend has
no more pages. Without orderBy, the db cannot know where it belongs.
Fix: give paginated queries an orderBy the loader can send. See
Pagination and Infinite Scroll.
Rows that do not belong
A list shows rows another query loaded
Symptom: drafts appear in a feed whose endpoint only returns published posts.
Cause: a list that is not paginated shows every held row that matches its conditions, whichever subset loaded
it. The endpoint filters by status on its own, and the db does not know.
Fix: declare it with fixed: { status: "published" } on that loader. See Loaders.
A filtered list is wrong, but only sometimes
Cause: the query was answered from held rows on a field the backend compares differently, such as case-insensitive or locale-aware titles. The client compares exactly.
Fix: mark the field serverOnly: ["title"] on the loader, so queries on it always go to the backend. See
Search and Server-side Filters for what that does and does not cover.
Data from the previous user after signing out
Fix: call await db.clear() on sign-out. It removes rows, loaded subsets, pending writes and the persisted data of
the scope, in every tab. With persistence, give each user their own scope. See
Offline-First Apps.
Writes that resolve with an error
result.error | Cause |
|---|---|
"post" already holds a row with the key ... | An insert of a key the collection holds |
An update cannot change the key of a row in "post" | An update whose changes include a different key |
Schema issues, with type: "validation" in db.onError | The write did not pass the collection's schema |
DependencyError | An earlier write to the same row, or one in dependsOn, failed |
An insert that leaves the key to the server cannot be made offline | Offline writes need client keys |
| The failed response's error | The server rejected the request |
All of these except the last one resolve without sending a request.
Requests you did not expect
| Symptom | Cause and fix |
|---|---|
| Every filter value sends a request | The loader declares the filter, so each value is its own subset. Leave it out if the list is small. |
| A list refetches on every window focus | Its subset is stale: no full sync coverage and staleTime passed. Raise staleTime or add syncs. |
| A list reloads after a reconnect | Expected: events may have been missed. Use resumes: true if your server replays them. |
| The same endpoint is called by a hook and the db | useFetch and a collection keep separate copies. Read that data through one of them. |
| A query loads again after leaving and returning | Its subset was released after gcTime. Raise gcTime in createDb to keep it longer. |
Runtime errors in your own code
TypeError: Cannot assign to read only property: stored rows are frozen, because every query and component shares them. Copy before changing:{ ...post, title }.- A field is still set after
update(key, { field: undefined }):undefinedmeans "no value". Sendnullto clear a field.
You know where to look when the db surprises you.
- You can read a query's plan with
explain(), and the whole db withinspect()or HyperFlow. - You can catch every failure with
db.onError. - You can fix queries that do not compile and
RowMismatcherrors. - You can trace a missing socket update, a foreign row or a flashing value to its cause.
- You can tell expected requests from unexpected ones.