# A power cut and writeFileSync emptied my database twice

Nujoom lost all its data twice, on July 23 and August 4. Both times the server came back up, connected to its database, and logged success. Both times the database was empty.

---

## How the file got emptied

The backend kept its database in [sql.js](https://github.com/sql-js/sql.js), which is SQLite compiled to WebAssembly and held entirely in memory. To keep it on disk, the server wrote the whole thing out every five seconds:

```js
setInterval(saveDB, 5000);

function saveDB() {
    if (!db) return;
    const data = db.export();
    fs.writeFileSync(DB_PATH, Buffer.from(data));
}
```

[`writeFileSync` truncates the file first](https://nodejs.org/api/fs.html#file-system-flags), then writes. For a moment, every five seconds, the file on disk is empty. The server ran at home, and in Syria the power cuts. If it cut inside that window, what was left on disk was a 0-byte file.

---

## Why nothing noticed

On the next start:

```js
if (fs.existsSync(DB_PATH)) {
    const fileBuffer = fs.readFileSync(DB_PATH);
    db = new SQL.Database(fileBuffer);
}
db.run(schema);
```

The file existed, so it was loaded. sql.js takes a 0-byte buffer as a perfectly good empty database. It's easy to check:

```js
const db = new SQL.Database(Buffer.alloc(0));
db.exec("SELECT count(*) FROM sqlite_master");  // 0 tables, no error
```

Then the schema ran, created every table fresh, and five seconds later the empty database was saved over the file. The log said connected.

The data helpers made it worse. The two read helpers, `getOne` and `getAll`, returned `null` or `[]` on any error, so a missing account looked the same as an account with no activity. For three weeks the loss read as "no data".

---

## Getting it back

None of it belonged to real families. Every account was one of our own test accounts. There were two copies to work from: one from July 21, with 25 parent accounts, and one from August 4, with the 3 made after the first loss. I merged them, shifting IDs so they couldn't collide, and imported the result: 28 parent accounts, 32 children, 3,120 activity records, 125 achievements, 142 chat messages.

---

## The fix was to stop owning the file

I moved the backend to Cloudflare Workers with D1. That removes this failure mode, and the platform stops depending on my house having power.

The port had its own work: all 151 database calls went async, and query patterns that were free against an in-memory database, like 5 queries per child on a parent's dashboard, became a network round trip each. Restored accounts kept their passwords.

And the helpers throw now.
