npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

pouchdb-relay

v0.1.0

Published

Multiplexed CouchDB _changes feed over WebSocket for PouchDB replication

Readme

pouchdb-relay

Multiplexed CouchDB _changes feed over WebSocket for PouchDB replication.

Problem

CouchDB filtered replication opens one continuous _changes feed per user. Each feed scans the entire changes sequence, making per-user sync expensive at scale. With prefix-based filtering (username-book:*), every connected user creates a separate server-side feed that walks the same global sequence.

Solution

pouchdb-relay multiplexes the _changes feed:

  • Server maintains ONE continuous _changes feed on the database
  • Clients connect via WebSocket and subscribe with their prefix
  • Server fans out matching changes to each client in real-time
  • All other replication calls (_revs_diff, _bulk_docs, _bulk_get, _local) pass directly to CouchDB

This reduces server load from O(users) change feeds to O(1).

Client Usage

import { createRelayFetch } from 'pouchdb-relay/client';

const relayFetch = createRelayFetch({
  relayUrl: 'wss://services.example.com/relay',
  originalFetch: PouchDB.fetch,
  getHeaders: async () => ({ Authorization: `Bearer ${token}` }),
  prefix: 'username',
});

const remoteDb = new PouchDB('https://couch.example.com/activities', {
  fetch: relayFetch,
});

// PouchDB replication works normally — _changes goes through
// the relay, everything else goes direct to CouchDB
remoteDb.sync(localDb, { live: true, retry: true });

// Clean up when done
relayFetch.destroy();

How it works

  1. createRelayFetch returns a fetch wrapper function
  2. When PouchDB calls fetch(url, opts):
    • If URL contains /_changes → route through WebSocket relay
    • Otherwise → call originalFetch(url, opts) directly to CouchDB
  3. For intercepted _changes requests:
    • Parse query params from the URL (since, heartbeat, feed, filter, selector)
    • Open/reuse a WebSocket connection to relayUrl
    • Send a subscribe message with the prefix and since value
    • Return a synthetic Response with a ReadableStream body that emits change events
  4. WebSocket lifecycle:
    • Auto-reconnect with exponential backoff (1s → 30s max)
    • Re-subscribe on reconnect with last known since
    • Ping/pong heartbeat to detect dead connections (25s interval, 10s timeout)
    • Clean close when PouchDB cancels replication (abort signal)

Options

interface RelayOptions {
  relayUrl: string;               // WebSocket URL of the relay server
  originalFetch: typeof fetch;    // PouchDB's fetch (for non-_changes requests)
  getHeaders: () => Promise<Record<string, string>>; // Auth headers
  prefix: string;                 // User's doc prefix for filtering
  reconnectBaseDelay?: number;    // Base delay in ms (default: 1000)
  reconnectMaxDelay?: number;     // Max delay in ms (default: 30000)
  heartbeatInterval?: number;     // Ping interval in ms (default: 25000)
  heartbeatTimeout?: number;      // Pong timeout in ms (default: 10000)
}

Server Protocol

The server is not included in this package. Below is the protocol specification for implementing the relay server.

WebSocket Messages

Client → Server:

// Subscribe to changes matching a prefix
{ "type": "subscribe", "prefix": "username", "since": "123-abc", "database": "activities" }

// Unsubscribe from changes
{ "type": "unsubscribe" }

// Heartbeat ping
{ "type": "ping" }

Server → Client:

// A matching change
{
  "type": "change",
  "seq": "124-def",
  "id": "username-book:abc",
  "changes": [{ "rev": "1-xyz" }],
  "deleted": false
}

// Periodic checkpoint (seq update without matching changes)
{ "type": "checkpoint", "seq": "200-ghi" }

// Heartbeat response
{ "type": "pong" }

// Error
{ "type": "error", "message": "Authentication failed" }

Server Responsibilities

  1. Single feed: Maintain ONE continuous _changes feed on the target database
  2. Fan-out: For each connected client, filter changes where doc._id.startsWith(prefix + '-')
  3. Immediate delivery: Send matching changes as they arrive
  4. Checkpoints: Send periodic checkpoint messages so clients can track since during quiet periods
  5. Authentication: Validate JWT from WebSocket connection params (passed as query string by the client)
  6. Prefix validation: Ensure the authenticated user matches the requested prefix

Server Implementation Notes

Single CouchDB _changes feed (continuous)
         │
         ▼
   ┌─────────────┐
   │ Relay Server │
   └─────┬───────┘
         │
    ┌────┼────┐
    ▼    ▼    ▼
  WS1  WS2  WS3   (one per connected client)
  user1 user2 user3

The relay maintains a map of prefix → Set<WebSocket>. On each change from the CouchDB feed:

  1. Extract the prefix from change.id (everything before the first -)
  2. Look up connected clients for that prefix
  3. Send the change to matching clients
  4. Periodically (e.g., every 10s or every 100 changes), send a checkpoint to all clients with the current seq