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

@synadiaorbit/counters

v1.1.0

Published

jetstream counter streams

Readme

counters

License JSR JSR Score NPM Version NPM Downloads

JetStream Counters

NATS server 2.12 introduced a JetStream counter feature that enables efficient counter CRDT (Conflict-free Replicated Data Type) operations that are order independent. A stream is set up for counters by enabling its allow_msg_counter and allow_direct options. Counter streams can only be used for counter operations, but can be aggregated and distributed across clusters and super-clusters.

Installation

# node, bun (esm and commonjs)
npm install @synadiaorbit/counters

# deno
deno add jsr:@synadiaorbit/counters

The npm package works with import and require, and requires Node.js 22 or later.

import { NewCounter } from "@synadiaorbit/counters";

Usage

The examples connect to the shared demo.nats.io server with wsconnect, which works in every runtime; any nats.js transport works too, see runtimes. Each one creates a stream of its own and deletes it when it is done.

Stream Setup

Counters need a stream with allow_msg_counter and allow_direct enabled; both options are required:

await jsm.streams.add({
  name: "counters",
  subjects: ["counters.>"],
  allow_msg_counter: true,
  allow_direct: true,
});

Counter streams reserve the payload of a message to maintain the counter values, so only counter operations are allowed on the stream. Messages expire with the stream's max_age, but the stream itself stays until it is deleted.

Basic Counter Operations

import { nanos, nuid, wsconnect } from "@nats-io/nats-core";
import { jetstreamManager } from "@nats-io/jetstream";
import { NewCounter } from "@synadiaorbit/counters";

const nc = await wsconnect({ servers: "wss://demo.nats.io:8443" });
const jsm = await jetstreamManager(nc);

// a stream of its own on the shared demo server; max_age expires the
// messages, and the finally block deletes the stream
const stream = `counters_${nuid.next()}`;
await jsm.streams.add({
  name: stream,
  subjects: [`${stream}.>`],
  allow_msg_counter: true,
  allow_direct: true,
  max_age: nanos(2 * 60 * 1000),
});

try {
  const counters = NewCounter(nc, stream);
  const logins = `${stream}.user_logins`;

  // Increment a counter
  const newValue = await counters.increment(logins, 1);
  console.log(`counter value: ${newValue}`);

  await counters.increment(logins, 100);

  // Get current counter value
  const currentValue = await counters.value(logins);
  console.log(`current value: ${currentValue}`);

  // Get counter with metadata
  const counter = await counters.getCounter(logins);
  if (counter) {
    console.log(`Value: ${counter.value}`);
    console.log(`Delta: ${counter.delta}`);
    console.log(`Subject: ${counter.subject}`);
    console.log(`Sequence: ${counter.seq}`);
    console.log(`Timestamp: ${counter.timestamp}`);
    console.log(`Time: ${counter.time}`);
  }
} finally {
  await jsm.streams.delete(stream);
  await nc.close();
}

Batch Operations

import { nanos, nuid, wsconnect } from "@nats-io/nats-core";
import { jetstreamManager } from "@nats-io/jetstream";
import { NewCounter } from "@synadiaorbit/counters";

const nc = await wsconnect({ servers: "wss://demo.nats.io:8443" });
const jsm = await jetstreamManager(nc);

// a stream of its own on the shared demo server; max_age expires the
// messages, and the finally block deletes the stream
const stream = `counters_${nuid.next()}`;
await jsm.streams.add({
  name: stream,
  subjects: [`${stream}.>`],
  allow_msg_counter: true,
  allow_direct: true,
  max_age: nanos(2 * 60 * 1000),
});

try {
  const counters = NewCounter(nc, stream);
  await counters.increment(`${stream}.logins`, 10);
  await counters.increment(`${stream}.errors`, 2);

  // Get multiple counter values using wildcards
  const vals = await counters.values(`${stream}.*`);
  for await (const value of vals) {
    console.log(`Counter value: ${value}`);
  }

  // Get multiple counters with metadata
  const counterObjects = await counters.getCounters([
    `${stream}.logins`,
    `${stream}.errors`,
    `${stream}.missing`,
  ]);
  for await (const counter of counterObjects) {
    console.log(`${counter.subject}: ${counter.value} (seq: ${counter.seq})`);
  }
} finally {
  await jsm.streams.delete(stream);
  await nc.close();
}

Counters that don't exist are skipped. If none of the names match a counter, iterating rejects with a no results error.

Historical Values

import { nanos, nuid, wsconnect } from "@nats-io/nats-core";
import { jetstreamManager } from "@nats-io/jetstream";
import { NewCounter } from "@synadiaorbit/counters";

const nc = await wsconnect({ servers: "wss://demo.nats.io:8443" });
const jsm = await jetstreamManager(nc);

// a stream of its own on the shared demo server; max_age expires the
// messages, and the finally block deletes the stream
const stream = `counters_${nuid.next()}`;
await jsm.streams.add({
  name: stream,
  subjects: [`${stream}.>`],
  allow_msg_counter: true,
  allow_direct: true,
  max_age: nanos(2 * 60 * 1000),
});

try {
  const counters = NewCounter(nc, stream);
  const logins = `${stream}.user_logins`;
  await counters.increment(logins, 1); // stored at sequence 1
  await counters.increment(logins, 100);

  // Get a counter value at a specific sequence number
  const historicalValue = await counters.value(logins, 1);
  console.log(`Value at sequence 1: ${historicalValue}`);

  // Get counter with metadata at a specific sequence
  const historicalCounter = await counters.getCounter(logins, 1);
  if (historicalCounter) {
    console.log(`Historical delta: ${historicalCounter.delta}`);
  }
} finally {
  await jsm.streams.delete(stream);
  await nc.close();
}

API Reference

NewCounter(nc: NatsConnection, stream: string, opts?: JetStreamOptions): Counters

Creates a new counter client instance.

Counters Interface

  • increment(name: string, delta: bigint | number): Promise<bigint> - Increment a counter with the specified delta, returns the new value
  • value(name: string, seq?: number): Promise<bigint | null> - Get counter value (optionally at a specific sequence)
  • getCounter(name: string, seq?: number): Promise<Counter | null> - Get counter with metadata
  • values(names: string[] | string): Promise<QueuedIterator<bigint>> - Get multiple values (supports wildcards)
  • getCounters(names: string | string[]): Promise<QueuedIterator<Counter>> - Get multiple counters with metadata

Counter Class

Properties available on counter objects:

  • value: bigint - The current counter value
  • delta: bigint - The increment/decrement amount for this revision
  • sources: CounterSources - For a counter that aggregates other counters through stream sources, the last value seen from each source, keyed by source stream and then by the subject in that source. Empty for a counter that isn't sourced
  • stream: string - The JetStream stream name
  • subject: string - The counter name/subject
  • seq: number - The sequence number in the stream
  • timestamp: string - The timestamp as a string
  • time: Date - The timestamp as a Date object

Features

  • Atomic Operations: All counter operations are atomic through JetStream
  • Historical Access: Retrieve counter values at any previous sequence
  • Batch Operations: Efficiently retrieve multiple counters at once
  • Wildcard Support: Use NATS subject wildcards in batch operations
  • Metadata Access: Get detailed information about each counter update

License

Apache License 2.0