Database / CouchDB Interview Questions
What is PouchDB and how does it enable offline-first applications with CouchDB sync?
PouchDB is an open-source JavaScript database that runs entirely inside the browser (using IndexedDB or WebSQL as the local storage backend) or in Node.js (using LevelDB). It implements the CouchDB replication protocol, which means it can sync bidirectionally with any CouchDB-compatible server — including Apache CouchDB and IBM Cloudant — using the same HTTP-based protocol.
The offline-first pattern works as follows:
- The browser app reads and writes to the local PouchDB instance — always available, zero latency, no network required.
- When connectivity is available, PouchDB syncs to the remote CouchDB server using the replication protocol: it pushes local changes and pulls remote changes.
- If two users edited the same document while offline, PouchDB surfaces the conflict the same way CouchDB does, and the application resolves it.
// Create a local PouchDB database
const localDB = new PouchDB('myapp');
// Write offline — works even without network
await localDB.put({ _id: 'order:001', type: 'order', total: 99.99 });
// Set up continuous two-way sync when online
const sync = localDB.sync('https://mycouch.example.com/myapp', {
live: true, // continuous
retry: true, // reconnect automatically on network failure
filter: 'myapp/user_docs', // optional: sync only relevant docs
});
sync.on('change', (change) => console.log('Synced:', change));
sync.on('error', (err) => console.error('Sync error:', err));
PouchDB is the canonical choice for progressive web apps, React Native apps, and any scenario where users need to work offline and sync reliably. The CouchDB replication protocol's idempotent, checkpoint-based design means a sync can be interrupted and resumed without data loss or duplicates.
More Related questions...