@bitdot/paginator
v2.0.0
Published
Backend-agnostic pagination with filters, async generators, and serial/parallel processing for MongoDB, Mongoose, MySQL and HTTP APIs
Readme
@bitdot/paginator
Backend-agnostic pagination and batch processing for Node.js.
One API to page through MongoDB, Mongoose, aggregation pipelines, MySQL and HTTP APIs — with a shared filter DSL, lazy async generators, and serial or parallel processing with backpressure, retries, rate limiting and crash-safe checkpoints.
npm install @bitdot/paginatorShips both ESM and CommonJS. Node 18.17+. Database drivers are injected, never imported — mongodb, mongoose and mysql2 are optional peers, so you only install what you use.
ES modules:
import { Paginator, MongoAdapter } from '@bitdot/paginator';CommonJS:
const { Paginator, MongoAdapter } = require('@bitdot/paginator');TypeScript declarations are included. Install the driver for the backend you use: mongodb 4+, mongoose 6+, or mysql2 3+. HTTP and in-memory pagination need no database driver.
Why
Reading a large table and doing something with each row looks easy until it isn't:
skip(N)/OFFSET Ndegrades linearly and eventually looks like a hang.- Long-lived database cursors expire mid-job.
- Sorting by a non-unique column silently skips rows at page boundaries.
- A transient network blip kills a six-hour job with no way to resume.
Promise.allover a million rows exhausts memory; a naive worker pool stalls when a handler throws.
This library handles all of those, once.
Adapter fetchPage({ filter, cursor, limit, signal }) -> { items, nextCursor }
| Mongo · Mongoose · Aggregate · MySQL · HTTP · Memory · yours
Paginator pages() · batches() · records() · for await
| prefetch, retry + backoff, page timeouts, rate limit, maxRecords, stuck-cursor guard
runPool serial or N workers, item or batch mode, error policy,
(.process()) per-item timeouts, ordered checkpoint watermarksQuick start
Try it without a database in an ES module (.mjs, or .js with "type": "module"):
import { Paginator, MemoryAdapter } from '@bitdot/paginator';
const pager = new Paginator(new MemoryAdapter([
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Lin' },
{ id: 3, name: 'Sam' },
]), { pageSize: 2 });
for await (const record of pager) {
console.log(record.name);
}For MongoDB, pass a connected collection and your record handler:
import { Paginator, MongoAdapter, F } from '@bitdot/paginator';
const adapter = new MongoAdapter(db.collection('orders'), { sort: { createdAt: 1 } });
const pager = new Paginator(adapter, {
filter: F.and(F.eq('status', 'paid'), F.gte('createdAt', new Date('2026-01-01'))),
pageSize: 1000,
});
// 1. Lazy and serial - consume one record at a time
for await (const order of pager) {
await ship(order);
}
// 2. A separate scan with up to 16 handlers in flight
const stats = await pager.process(
async (order, { signal }) => ship(order, signal),
{ concurrency: 16, onError: 'continue', onFailure: (err, o) => log(o._id, err) }
);
console.log(`${stats.succeeded} ok, ${stats.failed} failed in ${stats.durationMs}ms`);Each iteration or process() call starts a new scan from startCursor; reusing a paginator does not continue its previous scan.
Table of contents
- Adapters
- Filters
- Paginator options
- Processing
- Checkpoints and resuming
- Parallel fetching
- Logging
- Recipes
- Writing your own adapter
- Error types
- Performance notes
Adapters
| Adapter | Input | Strategies |
| --- | --- | --- |
| MongoAdapter(collection, opts) | driver Collection (a Mongoose Model is unwrapped automatically) | keyset (default), offset |
| MongooseAdapter(model, opts) | Mongoose Model — casts filters through the schema | keyset, offset |
| AggregateAdapter(collection, opts) | driver Collection + a pipeline | keyset, offset |
| MySqlAdapter(pool, opts) | mysql2/promise pool or connection | keyset (default), offset |
| HttpAdapter(opts) | a URL + fetch | cursor, page, offset, link, url |
| MemoryAdapter(rows, opts) | an array | keyset |
Every database page is an independent query. The scan does not hold one server-side cursor open for the duration of the job. Queries still need suitable indexes and timeouts, and concurrent data changes can affect the scan.
Keyset pagination, safely
Common options for the database adapters: sort and uniqueKey.
new MongoAdapter(coll, { sort: { createdAt: -1 }, uniqueKey: '_id' });
new MySqlAdapter(pool, { table: 'orders', sort: [['score', 'desc'], 'id'], uniqueKey: 'id' });- The unique key is always appended as a tiebreaker. Without it, rows sharing a sort value get skipped across page boundaries — the single most common keyset bug.
- Keyset fields are forced into the projection / column list, so a
select()that drops the sort field can't produce an infinite loop. - A missing or
nullkeyset value throwsCursorErrornaming the field, the record and the fix, rather than looping forever.
Keyset needs a composite index matching sort + tiebreaker:
Mongo: { createdAt: 1, _id: 1 }
MySQL: INDEX (created_at, id)MongoDB
import { MongoClient } from 'mongodb';
import { Paginator, MongoAdapter } from '@bitdot/paginator';
const client = await MongoClient.connect(process.env.MONGO_URL);
const adapter = new MongoAdapter(client.db('shop').collection('orders'), {
sort: { createdAt: 1 },
projection: { total: 1, status: 1 }, // _id and createdAt are added automatically
hint: 'createdAt_1__id_1',
maxTimeMS: 30_000,
findOptions: { readPreference: 'secondaryPreferred' },
});Mongoose
MongoAdapter talks to the native driver, which does no casting. A filter like { customerId: '1600' } or { _id: '65f…' } would match zero documents instead of erroring. MongooseAdapter casts the filter through the model's schema first:
import { Paginator, MongooseAdapter } from '@bitdot/paginator';
const adapter = new MongooseAdapter(Patient, {
sort: { updatedAt: 1 },
projection: 'name mrn', // select() string syntax works
lean: true, // default; set false to get hydrated documents
});
const pager = new Paginator(adapter, { filter: { customerId: '1600' }, pageSize: 500 });
// ^ cast to Number by the schemaThe cast filter is cached per filter object on the adapter. Cursor values come from real documents, so they are never re-cast. Use either an inclusion projection such as 'name mrn' or an exclusion projection such as '-ssn'; only _id can be excluded from an inclusion projection.
Middleware guard. Pages are read through Model.collection, so query middleware does not run. By default, construction throws if the model has find query middleware, including regex, plugin, inherited, and post hooks. To bypass known hooks intentionally, pass requireNoFindMiddleware: false and include tenant scoping, soft-delete criteria, and any other hook-added filters explicitly. Discriminator models are still scoped by their discriminator key. This guard checks find hooks; it does not execute middleware or enforce application authorization policies.
Strict casting. With castFilter: true (the default), the adapter sets strictQuery: 'throw' before casting. Unknown filter paths throw instead of being silently removed, including under Mongoose 6. Use strictQuery: false to preserve non-schema paths when that is intentional. strictQuery: true is rejected because it can strip criteria; castFilter: false skips casting entirely.
Aggregation pipelines
import { AggregateAdapter } from '@bitdot/paginator';
// keysetStage: 'pre' (default) - the keyset $match is pushed in front of your
// stages so it can use an index. Requires the sort field on the source documents.
const adapter = new AggregateAdapter(db.collection('claims'), {
pipeline: [
{ $lookup: { from: 'members', localField: 'memberId', foreignField: '_id', as: 'member' } },
],
sort: { _id: 1 },
allowDiskUse: true,
});
// keysetStage: 'post' - for pipelines that *compute* the sort field.
const grouped = new AggregateAdapter(db.collection('claims'), {
pipeline: [{ $group: { _id: '$memberId', total: { $sum: '$amount' } } }],
keysetStage: 'post',
});Keyset paging over a pipeline is only correct when the output is in a stable, unique order on sort + uniqueKey — and, in 'pre' mode, when every output document keeps the sort values of the source document it came from. The adapter enforces what it can:
- In keyset mode, stages that always break
'pre'($group,$bucket,$facet,$unionWith, …) throw at construction.$sampleis rejected for either pagination strategy because its output is non-deterministic. - Stages that may break it log a warning:
$unwind(fine for a to-one$lookup; passoneToOne: trueto say so),$limit/$skip, and stages that rewrite a sort field. A user$sortis harmless — the adapter's final$sortwins. - In keyset mode, a page holding two documents with identical keyset values throws
CursorError. Distinct composite$groupIDs are supported. This check only sees duplicates within a page; it does not prove the output keys are unique across the scan.
For an $unwind that produces multiple records per source document, use 'post' with sort fields that identify each output record, for example:
const lines = new AggregateAdapter(db.collection('orders'), {
pipeline: [{ $unwind: { path: '$lines', includeArrayIndex: 'lineIndex' } }],
keysetStage: 'post',
sort: { _id: 1, lineIndex: 1 },
uniqueKey: 'lineIndex', // the pair (_id, lineIndex) identifies an output record
});strategy: 'offset' supports repeated sort values in the pipeline output, but still needs a deterministic order and becomes slower as the offset grows. Set validatePipeline: false to skip the construction-time check; keyset duplicate validation still runs.
MySQL
import mysql from 'mysql2/promise';
import { MySqlAdapter } from '@bitdot/paginator';
const pool = mysql.createPool({ uri: process.env.MYSQL_URL });
const adapter = new MySqlAdapter(pool, {
table: 'analytics.events', // schema.table is validated and back-quoted
columns: ['id', 'user_id', 'payload'],
sort: { created_at: 'asc' },
uniqueKey: 'id',
keysetStyle: 'tuple', // or 'expanded' if EXPLAIN shows a bad plan
});All values are bound parameters and identifiers are validated against ^[A-Za-z_][A-Za-z0-9_$]*$, so field names cannot inject SQL.
Keyset cursor values must round-trip exactly. With mysql2's defaults, DATETIME(n)/TIMESTAMP(n) with n > 3 come back as JS Dates (milliseconds only) and BIGINT as JS numbers (exact only to 2^53), so sorting on such a column re-reads rows (ascending) or skips them (descending). Keep keyset columns at DATETIME(3) or below, or create the pool with dateStrings: true; for BIGINT keys use supportBigNumbers: true, bigNumberStrings: true.
HTTP APIs
import { HttpAdapter } from '@bitdot/paginator';
// 1. Opaque cursor token in the body
new HttpAdapter({ url: 'https://api.example.com/v1/orders', strategy: 'cursor' });
// 2. Page numbers
new HttpAdapter({ url: 'https://api.example.com/v1/orders', strategy: 'page', firstPage: 1, params: { limit: 'per_page' } });
// 3. RFC 8288 Link header
new HttpAdapter({ url: 'https://api.example.com/v1/orders', strategy: 'link' });
// 4. Next-page URL inside the body - handles { links: { next } }, HAL
// { _links: { next: { href } } } and relation arrays [{ relation: 'next', url }]
new HttpAdapter({ url: 'https://api.example.com/v1/orders', strategy: 'url', getItems: (b) => b.entry.map((e) => e.resource) });Other useful options:
new HttpAdapter({
url: 'https://api.example.com/v1/orders',
headers: async () => ({ authorization: `Bearer ${await freshToken()}` }), // refreshed per page
fetch: undiciFetch, // inject undici / a proxy agent / mTLS
getItems: (body) => body.data.records,
getNextCursor: (body) => body.meta.next,
getTotal: (body) => body.meta.total, // enables adapter.count()
hasMore: (body) => body.meta.has_more,
mapFilter: (f) => ({ since: f.value.toISOString() }),
parse: (res) => res.json(),
});408/429/5xx become retryable HttpErrors. A positive Retry-After value sets the minimum retry delay; a longer computed backoff still applies.
End of data. 'page' and 'offset' stop at the first empty page, not the first short one: many APIs cap the page size below the requested limit without saying so, and treating a short page as the last would end the scan after one page. That costs one extra request per scan; pass hasMore when the API reports it.
Page limit. A paginator using HttpAdapter defaults to maxPages: 10000, so a server that ignores paging parameters cannot keep a scan running forever. Set a smaller limit for the expected job size, or raise it for large scans:
const pager = new Paginator(new HttpAdapter({
url: 'https://api.example.com/v1/orders',
strategy: 'offset',
}), { maxPages: 1000 });If the source still reports more pages after the limit, iteration throws PageLimitError; process() wraps it in PoolError.cause. The last checkpoint stays resumable. The limit counts successful page responses, including empty continuation pages, but not retry attempts. maxPages: Infinity explicitly disables it. Other adapters default to Infinity; partitioned scans apply the limit per partition. Allow room for the final empty request with 'page' and 'offset'.
Origins. By default, every request must stay on the origin of url, or one listed in allowedOrigins. That covers next-page URLs from the response, the URL returned by buildRequest, and every redirect hop. Redirects are followed manually, up to maxRedirects (default 5), so each hop is checked. Relative next links resolve against the page they came from. Allowed origins receive the configured headers, including credentials.
new HttpAdapter({ url: 'https://api.example.com/v1/files', strategy: 'url', allowedOrigins: ['https://cdn.example.com'] });allowCrossOrigin: true disables origin checks. Setting init.redirect in buildRequest overrides the adapter's manual redirect handling; with 'follow', redirect destinations are handled by your fetch implementation rather than checked by the adapter.
Filters
F.eq F.ne F.gt F.gte F.lt F.lte F.in F.nin
F.exists F.contains F.startsWith
F.and F.or F.not F.rawThe DSL compiles to Mongo operators, parameterised SQL, query params, or an in-memory predicate:
const filter = F.and(
F.eq('status', 'paid'),
F.in('region', ['us', 'eu']),
F.gte('total', 100),
F.not(F.exists('deletedAt')),
);
toMongo(filter); // { $and: [ { status: { $eq: 'paid' } }, … ] }
toSql(filter); // { sql: '(`status` = ?) AND …', params: ['paid', …] }Native filters are accepted anywhere, including inside F.and(...):
F.and(
F.eq('status', 'paid'),
{ $expr: { $gt: ['$total', '$credit'] } }, // raw Mongo
);
F.and(F.eq('status', 'paid'), { sql: 'total > ?', params: [100] }); // raw SQLThe keyset condition is combined with your filter via $and / AND, so it can never clobber a condition on the same field.
NULL and missing-field behavior differs by backend, including
F.ne,F.nin, andF.not: SQL uses three-valued logic.F.containsandF.startsWithuse case-sensitive regexes in Mongo; MySQLLIKEfollows the column's collation.HttpAdapteronly mapseq/in/andgenerically — passmapFilterfor anything else.
Paginator options
| Option | Default | Purpose |
| --- | --- | --- |
| filter | null | DSL node or native filter |
| pageSize | 500 | requested records per fetch; HTTP APIs may return a different number |
| prefetch | 1 | pages fetched ahead of the consumer (0 = on demand) |
| delayMs | 0 | pause between pages |
| rateLimit | null | { tokens, intervalMs } or a shared RateLimiter |
| maxRecords | Infinity | hard cap (per partition when partitioned) |
| maxPages | 10000 for HTTP; Infinity otherwise | positive integer page limit per scan/partition; throws PageLimitError if more pages remain |
| startCursor | null | resume point from a checkpoint |
| pageTimeoutMs | 60000 | client timeout per fetch attempt; database adapters default to a server/driver budget of 90% of this value unless their timeout is configured explicitly |
| retry | 3 retries, exponential backoff + jitter | { retries, minDelayMs, maxDelayMs, factor, isRetryable } |
| signal | — | AbortSignal for cancellation |
| logger | omnilogger | any { debug, info, warn, error } |
| onPage | — | (page) => void \| Promise<void> after fetching, before processing; errors are logged |
| onCheckpoint | — | called after pages are fully handled by records()/batches() or process(); the pool can merge contiguous completions. A process() hook overrides the constructor hook |
Iteration
for await (const page of pager.pages()) { page.items; page.cursor; page.durationMs; }
for await (const rows of pager.batches()) { await bulkWrite(rows); }
for await (const row of pager.records()) { await handle(row); }
for await (const row of pager) { /* same as records() */ }Breaking out of any of these aborts the prefetch signal and closes the iterator. Adapters must honor the signal to cancel underlying work. pages() exposes fetch results and does not call onCheckpoint; when processing pages yourself, persist checkpointOf(page) only after handling all its records.
Counting
await pager.count(); // clamped to maxRecords
await pager.count({ estimated: true }); // Mongo metadata count when unfiltered; exact count otherwisePartitionedPaginator.count() counts each partition with its own filter, clamps each to
maxRecords and the total to maxRecordsTotal. Like Paginator.count(), it ignores
resume and startCursor — it reports the size of the scan, not how much of it is left. Estimated counting is adapter-specific; it does not make an HTTP or aggregation count approximate.
Processing
pager.process(handler, options) — or runPool(anyIterable, handler, options) for sources that aren't paginators.
| Option | Default | Purpose |
| --- | --- | --- |
| concurrency | 1 | max handlers in flight; 1 is serial and ordered |
| mode | 'item' | 'batch' passes each page's array (for bulk writes) |
| retries / retry | 0 | handler retries with backoff |
| onError | 'stop' | 'stop': no new work starts, in-flight finishes, rejects with PoolError. 'continue': send to onFailure and keep going |
| onFailureError | 'stop' | what to do when onFailure itself throws; see below |
| itemTimeoutMs | 0 | per attempt; aborts the handler's signal. JavaScript work cannot be force-cancelled: a handler that ignores signal keeps running while the retry or next unit starts, so it can exceed concurrency and repeat side effects. Honour the signal and keep handlers idempotent |
| signal | — | graceful shutdown → resolves with stats.aborted = true |
| collectResults | false | true or a numeric cap; see below |
| onResult / onFailure / onCheckpoint / onProgress | — | streaming hooks |
| progressIntervalMs | 5000 | how often onProgress fires (it may be async; a throw or rejection is logged, never fatal) |
| maxErrorSamples | 50 | how many errors are kept in stats.errors |
Returns stats:
{
processed, succeeded, failed, retried, pages,
inFlight, maxInFlight, durationMs, aborted,
errors, // sampled [{ error, unit }]
checkpoints, // { [partition]: Checkpoint }
results, // only when collectResults is set
resultsTruncated,
}Results are passed to onResult when provided and are not accumulated by default. The work queue is bounded to concurrency × 2. Checkpoint metadata can still grow when an early page is slow to finish or checkpoint persistence falls behind; completed page payloads are released. Keep handlers responsive and checkpoint writes fast. To retain a limited number of results:
const { results, resultsTruncated } = await pager.process(score, { collectResults: 10_000 });Error policy
// Fail fast: stop on the first error, let in-flight work finish, then throw.
try {
await pager.process(handler, { concurrency: 8 });
} catch (err) {
console.error(err.cause, err.stats.processed); // PoolError carries both
}
// Resilient: keep going, route failures somewhere durable.
await pager.process(handler, {
concurrency: 8,
onError: 'continue',
onFailure: (err, row) => deadLetter.insertOne({ row, error: err.message, at: new Date() }),
});If onFailure itself throws, the record was neither processed nor recorded. By
default that stops the run and holds the checkpoint behind the record, so a
resume retries it instead of losing it. Set onFailureError: 'continue' to get
log-and-advance back — appropriate when onFailure is just a console.error.
The asymmetry is deliberate: a failed onCheckpoint write is only ever logged,
because the worst case there is resuming from an earlier point. onProgress and
onPage are logged too — a metrics hook should not decide the outcome of a job.
Checkpoints and resuming
With 16 workers, page 7 can finish before page 6. runPool only advances the checkpoint across a contiguous run of fully processed pages, per partition, and persists them in order. Delivery is at-least-once: after a crash, processing resumes from the last persisted checkpoint and may repeat records. Use idempotent handlers and keep the source filter and sort stable across restarts. Pagination does not create a snapshot of a changing dataset.
import { serializeCursor, deserializeCursor } from '@bitdot/paginator';
import { ObjectId } from 'mongodb';
const saved = await jobs.findOne({ _id: 'nightly-sync' });
const checkpoint = saved?.cursor
? deserializeCursor(saved.cursor, { ObjectId })
: null;
// A completed scan has cursor: null too; check done before starting another scan.
if (!checkpoint?.done) {
const pager = new Paginator(adapter, {
pageSize: 1000,
startCursor: checkpoint?.cursor ?? null,
});
await pager.process(handler, {
concurrency: 16,
onCheckpoint: (cp) =>
jobs.updateOne({ _id: 'nightly-sync' }, { $set: { cursor: serializeCursor(cp) } }, { upsert: true }),
});
}serializeCursor preserves Date, BigInt and ObjectId. Pass the ObjectId constructor back in when deserializing — MongooseAdapter has a deserializeCursor(text) helper that wires it for you. A checkpoint has { partition, pageIndex, cursor, done }, plus partitionFingerprint when available. Save the entire checkpoint, including done; a null cursor with done: false means restart that partition.
With onError: 'continue', failed records count as handled (they went to onFailure); with 'stop' they hold the checkpoint back so a resume retries them.
A page cut short by maxRecords / maxRecordsTotal checkpoints back to itself
rather than past itself, so resuming re-reads that page instead of skipping the
records the cap dropped. Delivery is at-least-once throughout; handlers should be
idempotent.
Parallel fetching
concurrency in process() parallelises processing. When the fetch is the bottleneck, split the scan into independent key ranges:
import { PartitionedPaginator } from '@bitdot/paginator';
const pager = await PartitionedPaginator.byRange(adapter, {
field: 'id',
parts: 8,
pageSize: 2000,
filter,
maxRecordsTotal: 100_000, // global cap; maxRecords is per partition
rateLimit: { tokens: 20, intervalMs: 1000 }, // one limiter shared by all partitions
});
await pager.process(handler, { mode: 'batch', concurrency: 4, onCheckpoint: save });byRange reads MIN/MAX of the field (numbers, Dates, ObjectIds, numeric strings) and splits it evenly. You can also supply your own partition filters:
new PartitionedPaginator(adapter, [
F.eq('region', 'us'),
F.eq('region', 'eu'),
F.eq('region', 'apac'),
], { concurrency: 3, resume: savedByPartition });Order is preserved within a partition, not across them. Ranges split by value, so skewed data gives uneven partitions. HTTP cursor-token APIs cannot be partitioned, because each page depends on the previous one.
Resuming a partitioned job
resume is keyed by partition index, so it only means something against the same partition definitions. byRange computes its boundaries from the live MIN/MAX, so a restart after inserts would compute different ranges. Persist the boundaries with the checkpoints and pass them back:
const pager = saved
? await PartitionedPaginator.byRange(adapter, {
field: 'id', parts: 8,
bounds: deserializeCursor(saved.bounds), // identical partitions
resume: deserializeCursor(saved.checkpoints),
})
: await PartitionedPaginator.byRange(adapter, { field: 'id', parts: 8 });
await saveBounds(serializeCursor(pager.bounds)); // once, before processing
await pager.process(handler, { onCheckpoint: saveCheckpoint });When a partition filter can be fingerprinted, its checkpoint carries a partitionFingerprint. A mismatch with the current partition filter, or a checkpoint for an index that no longer exists, throws. Filters containing functions or cycles have no stable fingerprint, and older checkpoints may lack one, so preserve their partition definitions yourself. Keep the base filter, adapter sort, and unique key unchanged too; the fingerprint only identifies the partition filter.
For the built-in range adapters, pass an explicit field to byRange to expose pager.bounds for persistence. Custom adapters need rangeBounds() to support saving boundaries; rangePartitions() alone only supplies filters for the current run. Pass { ObjectId } to deserializeCursor when bounds or checkpoints contain MongoDB ObjectIds.
Logging
The default logger is @quicore/omnilogger. Page-level detail is logged at debug, so nothing appears until you lower the level:
import { setLogger, OmniLogger } from '@quicore/omnilogger';
setLogger(new OmniLogger({ level: 'debug' })); // or inject pino / winstonPer-instance override, or opt out entirely:
import { noopLogger } from '@bitdot/paginator';
new Paginator(adapter, { logger: pino({ level: 'debug' }) });
new Paginator(adapter, { logger: noopLogger });Recipes
Bulk-write in batches instead of row by row
await pager.process(
async (rows) => {
await target.bulkWrite(
rows.map((r) => ({
updateOne: { filter: { _id: r._id }, update: { $set: transform(r) }, upsert: true },
})),
{ ordered: false }
);
},
{ mode: 'batch', concurrency: 4 }
);One handler call per page, so pageSize becomes your write batch size.
Graceful shutdown under a process manager
const shutdown = new AbortController();
process.once('SIGTERM', () => shutdown.abort());
const stats = await pager.process(handler, { concurrency: 16, signal: shutdown.signal });
if (stats.aborted) {
await saveCheckpoint(stats.checkpoints); // resume from here next boot
process.exit(0);
}Aborting stops new work, lets in-flight handlers finish, and resolves (it does not throw).
Time-box each handler
A hung downstream call would otherwise occupy a concurrency slot forever. The timeout only signals the handler — it cannot stop code that ignores the signal — so pass signal on to every call that accepts one:
await pager.process(
async (row, { signal }) => fetch(url, { signal }), // honour the signal!
{ concurrency: 32, itemTimeoutMs: 15_000, retries: 2, onError: 'continue' }
);Respect a third-party rate limit
import { RateLimiter } from '@bitdot/paginator';
const limiter = new RateLimiter({ tokens: 10, intervalMs: 1000 }); // 10/s
// Limit the *fetch* side:
new Paginator(adapter, { rateLimit: limiter });
// Limit the *handler* side too, by sharing the same instance:
await pager.process(async (row) => {
await limiter.take();
return api.push(row);
}, { concurrency: 20 });A token is taken per fetch attempt, so retries are throttled as well.
Stream a large export to a file
import { createWriteStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';
import { Readable } from 'node:stream';
await pipeline(
Readable.from((async function* () {
for await (const row of pager.records()) yield `${row.id},${row.email}\n`;
})()),
createWriteStream('export.csv')
);Fan out from one source into several sinks
await pager.process(async (row) => {
const [a, b] = await Promise.all([warehouse.insert(row), search.index(row)]);
return { a, b };
}, { concurrency: 12, onError: 'continue' });Progress reporting with a known total
const total = await pager.count();
await pager.process(handler, {
concurrency: 16,
onProgress: (s) => {
const pct = ((s.processed / total) * 100).toFixed(1);
console.log(`${pct}% - ${s.processed}/${total}, ${s.failed} failed, ${s.maxInFlight} peak`);
},
});Dead-letter queue
await pager.process(handler, {
concurrency: 16,
retries: 3,
onError: 'continue',
onFailure: async (err, row) => {
await dlq.insertOne({ row, error: { message: err.message, stack: err.stack }, at: new Date() });
},
});Later, drain the queue by pointing a new paginator at the DLQ collection.
Process a plain array or async iterable
runPool does not require a paginator:
import { runPool } from '@bitdot/paginator';
await runPool(listOfFiles, (file) => convert(file), { concurrency: 8, onError: 'continue' });
await runPool(someAsyncIterable, (batch) => insertAll(batch), { mode: 'batch', batchSize: 500 });Join two sources without loading either into memory
for await (const batch of pager.batches()) {
const ids = batch.map((r) => r.userId);
const users = await db.collection('users').find({ _id: { $in: ids } }).toArray();
const byId = new Map(users.map((u) => [String(u._id), u]));
await sink.insertMany(batch.map((r) => ({ ...r, user: byId.get(String(r.userId)) })));
}Unit-test your handler without a database
import { Paginator, MemoryAdapter } from '@bitdot/paginator';
const adapter = new MemoryAdapter(rows, {
latencyMs: 5,
onFetch: ({ cursor }) => { if (cursor) throw new Error('boom'); }, // inject a failure
});
const stats = await new Paginator(adapter, { pageSize: 10 })
.process(handler, { onError: 'continue' });Deterministic ordering across restarts
Always sort on something immutable. Sorting by updatedAt while the job mutates updatedAt makes records move underneath the cursor:
new MongoAdapter(coll, { sort: { updatedAt: 1 } }); // risky if the handler touches updatedAt
new MongoAdapter(coll, { sort: { _id: 1 } }); // stableMore runnable examples live in examples/.
Writing your own adapter
One required method:
class ElasticAdapter {
name = 'elastic:orders';
async fetchPage({ filter, cursor, limit, signal, timeoutMs }) {
const res = await client.search({
index: 'orders',
size: limit,
sort: [{ created_at: 'asc' }, { _id: 'asc' }],
search_after: cursor?.values,
query: toElastic(filter),
}, { signal });
const items = res.hits.hits.map((h) => h._source);
return {
items,
nextCursor: items.length < limit ? null : { values: res.hits.hits.at(-1).sort },
};
}
// Optional
async count(filter) { /* … */ }
async rangeBounds({ field, parts, filter }) { /* return interior boundary values */ }
async rangePartitions({ field, parts, filter }) { /* … */ }
isRetryable(err) { return err.statusCode >= 500; }
// Set this when the cursor is derived from the limit (page number x limit).
// The paginator then always requests a full pageSize and trims locally,
// instead of shrinking the last request and shifting every page boundary.
fixedPageSize = false;
}Verify it against the conformance suite:
import { checkAdapterConformance } from '@bitdot/paginator/testing';
const { failed, results } = await checkAdapterConformance(async (rows) => ({
adapter: new ElasticAdapter(await seed(rows)),
cleanup: () => teardown(),
}));
assert.equal(failed, 0, results.filter((r) => !r.ok).map((r) => r.name).join(', '));It covers empty sources, partial and exact-multiple page counts, duplicate sort values at boundaries, ordering, mid-stream resume, abort, early break, maxRecords and count().
Error types
| Error | When | Retryable |
| --- | --- | --- |
| TimeoutError | a page or handler attempt exceeded its timeout | yes |
| HttpError | non-2xx response; carries status, body, retryAfterMs | 408/429/5xx |
| CursorError | missing/null keyset value, duplicate aggregation keyset values within a page, or a repeated cursor | no |
| PageLimitError | maxPages reached while the source reports more pages; checkpoint remains resumable | no |
| PoolError | fatal handler, failure-hook, or source error; carries .cause and .stats | n/a |
| AbortError | cancelled via signal | no |
Default fetch retry classification covers ECONNRESET, ETIMEDOUT, EAI_AGAIN, undici socket errors, MySQL deadlocks, lock and query timeouts, Mongo network/selection errors and MaxTimeMSExpired, and fetch failed. Override with retry: { isRetryable } or an adapter-level isRetryable(err). Handler retries are configured separately through process().
Performance notes
- Index your sort. Keyset pagination needs an index covering the sort fields plus the tiebreaker, in that order. Without it, every page is a full scan.
pageSizeis a round-trip/latency trade-off. 500–2000 suits most databases; HTTP APIs are usually capped by the vendor.prefetchoverlaps the next fetch with the current page's processing.prefetch: 2is typically enough; higher mostly buys memory.concurrencyis not free. For I/O-bound handlers, raise it until the downstream saturates. For CPU-bound work, a worker pool beats raising it past core count.- MySQL tuple comparisons.
(a, b) > (?, ?)is the default keyset form. Index range use for row constructors varies by MySQL version — runEXPLAIN, and setkeysetStyle: 'expanded'if the plan looks wrong. - Prefer
mode: 'batch'for writes. One bulk write per page beats N round trips.
API surface
import {
// core
Paginator, PartitionedPaginator, partitionFingerprint, runPool, checkpointOf, Channel,
// adapters
MongoAdapter, MongooseAdapter, AggregateAdapter, MySqlAdapter, HttpAdapter, MemoryAdapter,
ensureProjection, parseProjection, checkPipeline, parseLinkHeader, parseRetryAfter,
// filters
F, isFilterNode, toMongo, toSql, toPredicate, quoteIdent, rangeFilters,
// cursors + helpers
serializeCursor, deserializeCursor, normalizeSort, splitRange,
RateLimiter, retry, sleep, withTimeout, isRetryableError,
// errors
TimeoutError, AbortError, HttpError, CursorError, PageLimitError, PoolError, ChannelClosedError,
// logging
defaultLogger, noopLogger,
} from '@bitdot/paginator';
// Types (Checkpoint, Page, PoolStats, adapter option shapes) are exported too.
import type { Checkpoint, PoolStats } from '@bitdot/paginator';
import { checkAdapterConformance } from '@bitdot/paginator/testing';License
MIT
