Skip to content
TypeScript

fix(server): stop fsyncing SQLite on every commit so slow disks no longer drop clients (#19205)

Theo Brownea74ce48f9630
diff --git a/apps/server/src/persistence/Sqlite.test.ts b/apps/server/src/persistence/Sqlite.test.ts
index 666e14d3a5c..f4056c9d0c2 100644
--- a/apps/server/src/persistence/Sqlite.test.ts
+++ b/apps/server/src/persistence/Sqlite.test.ts
@@ -114,6 +114,21 @@ it.effect("collects planner statistics for an existing database on open", () =>
);
});
+it.effect("only fsyncs the database file at WAL checkpoints", () => {
+ const tempDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-sqlite-sync-"));
+ const dbPath = NodePath.join(tempDir, "state.sqlite");
+
+ return Effect.gen(function* () {
+ const sql = yield* SqlClient.SqlClient;
+ const rows = yield* sql<{ readonly synchronous: number }>`PRAGMA synchronous`;
+ // 1 is NORMAL.
+ assert.equal(rows[0]?.synchronous, 1);
+ }).pipe(
+ Effect.provide(SqlitePersistence.layerFromPath(dbPath).pipe(Layer.provide(NodeServices.layer))),
+ Effect.ensuring(Effect.sync(() => NodeFS.rmSync(tempDir, { recursive: true, force: true }))),
+ );
+});
+
it.effect("applies busy_timeout in the shared persistence setup", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
diff --git a/apps/server/src/persistence/Sqlite.ts b/apps/server/src/persistence/Sqlite.ts
index 2ea5199b283..d6adf41f3d9 100644
--- a/apps/server/src/persistence/Sqlite.ts
+++ b/apps/server/src/persistence/Sqlite.ts
@@ -19,6 +19,12 @@ const layerSetup = Layer.effectDiscard(
yield* sql`PRAGMA busy_timeout = 5000;`;
yield* sql`PRAGMA foreign_keys = ON;`;
yield* sql`PRAGMA journal_mode = WAL;`;
+ // FULL fsyncs the WAL on every commit, on the main thread. Every provider
+ // event is its own commit, so a slow or busy disk stalls the event loop
+ // and clients drop. In WAL mode NORMAL only fsyncs at checkpoints. It
+ // cannot corrupt the database and an app crash loses nothing; an OS crash
+ // or power loss can roll back commits since the last checkpoint.
+ yield* sql`PRAGMA synchronous = NORMAL;`;
// PASSIVE checkpoints never shrink the -wal file, so it otherwise keeps its
// largest size until the last connection closes.
yield* sql.unsafe(`PRAGMA journal_size_limit = ${WAL_SIZE_LIMIT_BYTES};`);