DEV Community

Kinetic Code Labs
Kinetic Code Labs

Posted on Originally published at kineticcodelabs.in

Hybrid SQLite + Neon PostgreSQL Sync: Fixing Ephemeral Container Data Resurrection

Why Hybrid SQLite + Postgres?

Running node:sqlite in WAL mode inside our Node.js process gives Bondly microsecond-level query latency for feeds, hydrated comments, and search—without network round-trips on every request. To survive container restarts on Render's ephemeral disk, we pair it with Neon PostgreSQL, hydrating SQLite on boot and syncing writes asynchronously.


The Subtle Sync Bug: "Zombie" Messages and Stories

After shipping, we hit a baffling bug: users would unsend a message or delete a story, see it vanish, and then see it reappear after the next backend deployment.

Here is why it happened:

  1. DELETE /api/messages/:id?mode=unsend and DELETE /api/stories/:id only ran DELETE on local SQLite.
  2. Our periodic syncAllToPg() function only looped through existing SQLite rows and ran INSERT ... ON CONFLICT DO UPDATE into Postgres.
  3. Because the deleted row no longer existed in SQLite, syncAllToPg() never touched its twin in Postgres! On the next deploy, initCloudSql() faithfully restored the "deleted" row from Postgres back into SQLite.
  4. Furthermore, for "Delete for everyone" (mode=everyone), our Postgres ON CONFLICT DO UPDATE updated content and deleted_for_everyone, forgetting to clear media_url and media_type.

The Fix: Write-Through Deletes & Idempotent Cleanups

We added dedicated write-through helpers in pgSync.js:

async function deleteMessageFromPg(messageId) {
  const p = getSqlPool();
  if (!p || !messageId) return;
  await p.query('DELETE FROM bondly_messages WHERE id = $1', [messageId]);
}

async function deleteStoryFromPg(storyId) {
  const p = getSqlPool();
  if (!p || !storyId) return;
  await p.query('DELETE FROM bondly_story_replies WHERE story_id = $1', [storyId]);
  await p.query('DELETE FROM bondly_story_reactions WHERE story_id = $1', [storyId]);
  await p.query('DELETE FROM bondly_stories WHERE id = $1', [storyId]);
}
Enter fullscreen mode Exit fullscreen mode

We also added media_url = EXCLUDED.media_url, media_type = EXCLUDED.media_type to syncMessageToPg() and guarded demo data seeding behind SEED_DEMO_DATA === 'true' so production wipes stay permanently clean.

Free Engineering & AI Search Diagnostics

Originally published at Kinetic Code Labs.

Top comments (0)