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

driftless-cdc

v0.3.0

Published

Keeps Meilisearch indexes and a Redis cache in sync with PostgreSQL by reading the WAL (logical replication), with zero drift you can check.

Downloads

404

Readme

Driftless

CI

Keeps Meilisearch indexes and a Redis cache in sync with Postgres tables by reading the database's write-ahead log, and proves they never drift apart, even when the sync process (or Redis itself) is killed mid-write.

The usual way to keep search in sync is a dual write: the app saves to Postgres, then also updates the search index. When the second write fails, or two requests race, the index silently disagrees with the database, and nobody notices until a customer searches. Driftless removes the second write. The app writes only to Postgres. Driftless streams every committed change out of Postgres's WAL (logical replication) and applies it to Meilisearch and to a Redis cache, at least once and in commit order per row, and it tells Postgres "done" only after the change is really in both.

Written in TypeScript on Node 24 (run directly, no build step). Postgres 17, Meilisearch 1.54, Redis 8, Docker Compose.

Results

Every number below comes from a recorded run in docs/RESULTS.md, with its exact command, date, versions and machine (Windows 11, Docker Desktop, 28 CPUs / 7.6 GiB visible to Docker).

| What | Result | |---|---| | Correctness under crashes | 0 missing / 0 extra / 0 mismatched documents out of 261,113, after 1,197,314 transactions at 1,000 tx/s with the connector SIGKILLed 36 times (about every 30 s for 20 min). §1 | | Freshness (commit in Postgres → searchable) | p99 3.6 s at 500 tx/s, 4.9 s at 1,000 tx/s. Kept up with ~4,800 tx/s, the most the machine's Postgres could generate. Lag ≈ 2 × one Meilisearch write, most of which is Meilisearch's own indexing. §8 | | Throughput (draining a backlog) | 9 → 6,752 tx/s from batching across transactions + 8 parallel ordered lanes (on a ~105k-document index; 2,810 tx/s on a 195k-document one, since Meilisearch's per-batch cost grows with the index). §4, §9 | | Backfill while the table is being written | 0 drift in 10 / 10 races (≈105 race windows each), using DBLog-style watermarks. §5 | | Meilisearch down for 5 minutes at 600 tx/s | memory stayed bounded (backpressure; uncapped it grew 45 → 220 MiB and kept rising), connection kept alive, 0 drift after. §6 | | Driftless down for too long | Postgres gives up the slot at a 1 GB WAL cap instead of filling its disk; Driftless refuses to run on a lost slot and prints the recovery steps; recovery tested at 0 drift. §7 | | Several tables, one stream | Two tables (290k + 20k rows) × two sinks stayed exact through 11 SIGKILLs under transactions that change both tables at once, a backfill race with 7 SIGKILLs (it resumed, never restarted), and adding, removing and re-adding a table on a running deployment. §13 | | Redis cache, never stale | 0 drift in the cache under connector SIGKILLs, a 2-minute Redis freeze, and a SIGKILL of Redis itself. With Redis's default persistence, the same crash left 6,238 wrong keys (4,143 rolled back to older values), which is why Driftless runs it with appendfsync always. Cost: ~0.15 s of lag at 1,000 tx/s. §12 |

Every push re-proves the main claim. CI type-checks, runs the unit tests, then starts the real stack on the runner: it seeds two tables, lets Driftless backfill both indexes and the cache, SIGKILLs the connector about every 10 s under 200 tx/s of writes (cross-table transactions included), and fails unless reconcile finds 0 drift in every table and sink (scripts/ci-e2e.sh).

Grafana during a crash test

The provisioned dashboard during scripts/chaos.sh 240 30 300: 4 minutes at 300 tx/s with a SIGKILL about every 30 s. Each kill shows as a gap in "Connector up" and a lag spike while the restarted connector replays unconfirmed work. Backpressure never engaged, and once the run ended the WAL held for the slot drained to 56 bytes. Reconcile afterwards: 279,180 rows = 279,180 documents, 0 drift.

Bugs found on the way, each with a repro and a write-up: a replication library acknowledging one byte too far (BUG-001), a backfill race that wrote stale rows back (BUG-002), the watermark algorithm assuming full row images when Postgres omits unchanged TOAST columns (BUG-003), and an HTTP 408 treated as fatal (BUG-004).

How it works

flowchart LR
  app[App] -->|writes only here| pg[(Postgres<br/>WAL)]
  pg -->|logical replication<br/>slot + pgoutput| decode[Decode &<br/>assemble txns]
  decode --> route{"hash(id) % N"}
  route --> l1[lane 1]
  route --> l2[lane …]
  route --> ln[lane N]
  l1 & l2 & ln -->|batched, coalesced<br/>upserts / deletes| meili[(Meilisearch)]
  l1 & l2 & ln -->|same batch,<br/>one MULTI| redis[(Redis cache)]
  meili & redis -->|both applied| cp[Checkpointer]
  cp -->|confirm LSN<br/>only after apply| pg
  bf[Backfill<br/>with watermarks] -.->|existing rows| route
  1. Read the WAL, never dual-write. A replication slot makes Postgres keep every change until Driftless confirms it, across restarts.
  2. Confirm only after apply, in every sink. A transaction's end position is confirmed only once Meilisearch and Redis have applied every one of its changes, and only once everything before it is too: the checkpointer confirms the end of the unbroken run of applied transactions. A crash at any moment replays from the last confirmed point.
  3. Replays are harmless. Writes are idempotent upserts and deletes by primary key, so at-least-once delivery has an exactly-once effect.
  4. Order per row, parallel across rows. Changes are routed by a hash of the primary key into N ordered lanes, so one row's changes are never reordered, while different rows' changes are written in parallel.
  5. Batch without a timer. When a lane's write finishes, it sends everything that queued up meanwhile (up to 5,000), merged per key. A quiet system writes each change at once; a busy one sends big batches.
  6. Fail-stop. On any error it can't safely retry, Driftless exits; Docker restarts it and it resumes from the slot.
  7. Backpressure, not buffering. At 50,000 waiting changes it stops reading the socket. TCP pushes back and the backlog waits in Postgres's WAL, which was keeping it anyway.
  8. A cache that is never stale. Only Driftless writes the cache, from the commit-ordered WAL (readers never fill it on a miss), so the classic cache-aside race can't put an old value back. Redis acknowledges a write only once it's in its fsynced append-only file, so a Redis crash can't roll a key back either (D-029).

The full design is in docs/ARCHITECTURE.md, every choice and its reason in docs/DECISIONS.md, and step-by-step flows in docs/FLOW.md.

Use it with your own database

Write a config file for your tables, then run Driftless as a container (amd64 and arm64):

docker run -d --name driftless --restart unless-stopped -v "$PWD/driftless.config.json:/app/driftless.config.json:ro" -e PGPASSWORD -e MEILI_MASTER_KEY -e REDIS_PASSWORD -e DRIFTLESS_METRICS_HOST=0.0.0.0 -p 127.0.0.1:9464:9464 ghcr.io/kunal874/driftless:0.3.0

Or with Node.js ≥ 24, from npm (package driftless-cdc, command driftless):

npx driftless-cdc --config driftless.config.json

Check every row against its document and cache entry at any time (read-only; exit code 0 = no drift):

npx driftless-cdc reconcile --config driftless.config.json
  • Secrets come from the environment only (PGPASSWORD, MEILI_MASTER_KEY, REDIS_PASSWORD), never from the file.
  • Inside a container, 127.0.0.1 is the container itself: put real host names in the config.
  • Run one Driftless per replication slot, and restart it when it exits (--restart, systemd, …): it stops on purpose when something needs a person, and resumes from the slot when started.
  • Set max_slot_wal_keep_size on Postgres and use the alerts.

Quick start

Needs Docker (with Compose v2), Node.js ≥ 24 and bash (on Windows: Git Bash).

git clone https://github.com/Kunal874/driftless.git
cd driftless && npm ci

Start Postgres (with wal_level=logical), Meilisearch and Redis. All are bound to 127.0.0.1, with local-dev credentials:

docker compose up -d --wait

Create 100,000 demo products and 20,000 customers (on Windows Git Bash, put MSYS_NO_PATHCONV=1 in front):

docker compose exec -T postgres psql -U driftless -d shop -f /db/seed.sql
docker compose exec -T postgres psql -U driftless -d shop -f /db/seed-customers.sql

Start Driftless. It mirrors both tables (as configured): it sees empty indexes and an empty cache, copies the existing rows (backfill, one table at a time), then streams new changes:

docker compose --profile connector up -d --build connector
docker compose logs -f connector

Write to Postgres (a random mix of updates, inserts and deletes on both tables, some transactions changing a product and a customer together, at 200 tx/s for 30 s), then check every row against its document and its cache entry:

WORKLOAD_MIX=multi scripts/workload.sh 200 30
node scripts/reconcile.ts

It should end with OK: no drift. Search the index:

curl -s http://127.0.0.1:7700/indexes/products/search -H 'Authorization: Bearer driftless-dev-master-key' -H 'Content-Type: application/json' -d '{"q":"chair","limit":3}'

Read one product from the cache (each field is JSON):

docker compose exec redis redis-cli HGETALL product:7

Dashboards (Prometheus + Grafana, then open http://127.0.0.1:3000):

docker compose --profile metrics up -d

And the crash test: SIGKILL the connector about every 30 s for 10 minutes under load, then reconcile:

scripts/chaos.sh 600 30 200

Configuration

What to sync where lives in driftless.config.json (or the file DRIFTLESS_CONFIG points to):

{
  "postgres": { "host": "127.0.0.1", "port": 5440, "user": "driftless", "database": "shop" },
  "meilisearch": { "host": "http://127.0.0.1:7700" },
  "sync": [
    { "table": "public.products", "index": "products", "primaryKey": "id", "redisKeyPrefix": "product:",
      "columns": { "exclude": ["description"] } },
    { "table": "public.customers", "index": "customers", "primaryKey": "id", "redisKeyPrefix": "customer:" }
  ],
  "redis": { "url": "redis://127.0.0.1:6381" }
}

sync lists the tables to mirror, each into its own index and Redis key prefix (a single object works too). Adding a table to a running deployment backfills just that table; removing one stops mirroring it. columns is optional: include (a list that must contain the primary key) or exclude; without it, every column becomes a document field (and a cache field). redis is optional too: without it, Driftless keeps only the indexes. Switching it on fills the cache by itself (a backfill starts for any table with an empty sink). The file is validated in full at start, every problem reported at once (including duplicate tables, indexes or overlapping key prefixes). Then it's checked against the real tables (primary keys must match, named columns must exist) before anything is created. Secrets are refused in the file, including a password inside the Redis URL: they come from environment variables.

Environment variables override the file or tune the pipeline:

| Variable | Default | | |---|---|---| | PGHOST PGPORT PGUSER PGDATABASE | from the file | standard Postgres variables | | PGPASSWORD | driftless (local dev) | never in the file | | MEILI_HOST | from the file | | | MEILI_MASTER_KEY | driftless-dev-master-key (local dev) | never in the file | | REDIS_URL | from the file | only when the file has a redis section | | REDIS_PASSWORD | none (local dev) | never in the file | | DRIFTLESS_LANES | 8 | parallel ordered lanes. 1 gives the lowest steady lag on Meilisearch, 8 the fastest catch-up (D-027) | | DRIFTLESS_BATCH_MAX | 5000 | most changes in one write | | DRIFTLESS_MAX_PENDING | 50000 | stop reading the stream at this many waiting changes; resume at half | | DRIFTLESS_BACKFILL | off | 1 = copy all existing rows on start (it also starts by itself when the index or the cache is empty and the table isn't) | | DRIFTLESS_BACKFILL_CHUNK | 10000 | rows per backfill chunk | | DRIFTLESS_METRICS_HOST / _PORT | 127.0.0.1 / 9464 | GET /metrics | | DRIFTLESS_LOG_TXNS | off | 1 = log every transaction |

Postgres needs wal_level=logical, and the table needs a single-column primary key with REPLICA IDENTITY DEFAULT or FULL. Driftless creates its own publication, slot and two small bookkeeping tables (driftless_watermark, driftless_state).

Observability

GET :9464/metrics serves Prometheus metrics:

  • driftless_lag_seconds: commit → applied and confirmable;
  • driftless_write_seconds{sink} (one write to Meilisearch or Redis) and driftless_batch_changes;
  • driftless_changes_applied_total{op};
  • the gauges changes waiting, transactions in flight, reading paused and confirmed LSN;
  • driftless_slot_retained_wal_bytes, the WAL Postgres keeps for the slot, and driftless_slot_safe_wal_bytes, how much more it may keep before it invalidates the slot.

The metrics profile adds Prometheus and a provisioned Grafana dashboard (docker/), with the alerts on top.

Cap the slot's WAL. Postgres keeps WAL for a stopped Driftless until its disk is full, unless you set max_slot_wal_keep_size (e.g. 1GB; the compose file does). With a cap, Postgres gives the slot up instead, and Driftless refuses to start until you recover (docs/ROLLBACK.md). Driftless warns at startup when there's no cap.

Alerts. docker/prometheus/alerts.yml holds five Prometheus rules. To use them in your own Prometheus, list the file under rule_files: and scrape Driftless as job driftless (or change that label in the file). Send them on with your own Alertmanager.

| Alert | Fires when | Severity | |---|---|---| | DriftlessDown | Prometheus can't scrape Driftless for 2 min | critical | | DriftlessStalled | transactions are waiting but nothing was applied for ~5 min (a sink is down or failing) | critical | | DriftlessLagHigh | lag p99 > 60 s for 10 min | warning | | DriftlessSlotWalHigh | the slot holds over 50 % of max_slot_wal_keep_size for 5 min | warning | | DriftlessSlotWalCritical | over 80 % for 1 min: next comes invalidation and a full backfill | critical |

The slot alerts use the share of the cap (retained / (retained + safe)), so they work for any cap; without a cap they can't fire. Each one was made to fire on the real stack (RESULTS §14), and promtool test rules checks them in CI.

Testing

npm test
npm run typecheck

Unit tests cover decoding, the checkpointer, lanes, coalescing, the retry policy, backfill watermarks, backpressure and config validation. The claims are proven by scripts against the real stack:

| Script | Proves | |---|---| | scripts/ci-e2e.sh [ROWS] [CHAOS_SECONDS] | what CI runs: fresh stack → backfill → SIGKILL chaos → reconcile 0 → self-test (locally: COMPOSE_PROJECT_NAME=driftless-ci) | | scripts/reconcile.ts [--self-test] | every row equals its document (the self-test plants drift and demands it's found) | | scripts/chaos.sh DURATION KILL_EVERY RATE | 0 drift with random SIGKILLs under load | | scripts/backfill-race.sh DELAY RATE SECONDS [KILL_EVERY] | backfill racing concurrent writes (and crashes) | | scripts/slow-sink.sh PAUSE RATE MAX_PENDING [SERVICE] | bounded memory while Meilisearch (or redis) is frozen | | scripts/alert-drill.sh down\|stalled\|slot [RATE] | each alert fires for real, then resolves (needs the metrics profile) | | scripts/redis-crash.sh always\|everysec\|rdb | SIGKILL Redis under load, then reconcile the cache (own compose project) | | scripts/bench-drain.sh LANES BATCH_MAX RATE SECONDS | backlog drain throughput | | node scripts/bench-lag.ts RATE SECONDS CLIENTS | end-to-end lag quantiles at a fixed write rate | | node scripts/repro-ack-off-by-one.ts | reproduces BUG-001 |

Limitations

  • Several tables per instance, all from one database (one slot); single-column primary keys; plain lower-case table names. Changing a table's column filter needs a forced backfill to rewrite its documents.
  • Two sinks: Meilisearch and Redis (each one module behind src/sinks/sink.ts). Every write waits for the slower one, which is Meilisearch.
  • Schema changes (ALTER TABLE) are untested. A dropped column's old values would stay in documents until each row is rewritten or a fresh backfill runs.
  • A slot lost to the WAL cap needs manual recovery (on purpose: it involves deleting the index). docs/ROLLBACK.md has the steps.
  • Numbers come from one developer machine, with other containers running; treat them as relative, not absolute.

Repository guide

| | | |---|---| | src/ | the connector (tests next to code as *.test.ts) | | scripts/ | workload, reconcile, chaos, benchmarks | | db/ | schema, seed, workload SQL | | docs/ | architecture, decisions, flows, results, bugs, rollback, build plan | | learn/ | one plain-language write-up per build task: what was done, why, and what went wrong |

License

MIT