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

@printhive/mqtt

v0.6.0

Published

A fast MQTT 3.1.1 client for Effect, on Bun and Node.js

Readme

@printhive/mqtt

A fast MQTT 3.1.1 client for Effect, on Bun and Node.js.

  • QoS 0, 1, and 2 in both directions, retained messages, wills, and TLS.
  • Reconnects with an Effect Schedule, resends unfinished QoS 1 and 2 messages when the broker kept the session, and resubscribes when it did not.
  • Subscriptions are scoped streams with bounded buffers. A slow consumer makes the client stop reading, so TCP pushes back on the broker instead of memory growing.
  • No runtime dependencies besides the effect peer dependency. It runs on node:net and node:tls, which Bun also implements.
  • About 4 times faster than mqtt.js at decoding packets, and 1.2 to 1.7 times its end-to-end QoS 0 throughput. See Performance.

Install

bun add @printhive/mqtt effect
# or
npm install @printhive/mqtt effect

It needs Node.js 22 or later, or Bun.

Publish and subscribe

import { Buffer } from "node:buffer"
import * as Effect from "effect/Effect"
import * as Stream from "effect/Stream"
import { connect } from "@printhive/mqtt"

const program = Effect.gen(function* () {
  const client = yield* connect({ host: "broker.example.com", tls: true }) // your broker
  const messages = yield* client.subscribe("printers/+/status", { qos: 1 })

  yield* client.publish("printers/p1s/status", "printing", { qos: 1 })

  yield* messages.pipe(
    Stream.take(1),
    Stream.runForEach((m) => Effect.log(m.topic, Buffer.from(m.payload).toString()))
  )
})

Effect.runPromise(Effect.scoped(program))

The client stays connected until its scope closes, or until client.close(). Either one sends DISCONNECT, so the broker does not publish the client's will, and completes only once the socket is gone. A broker that does not hang up within connectTimeout has its socket destroyed. client.close({ force: true }) destroys the socket at once without DISCONNECT, for a link already known to be dead; the broker then publishes the will.

subscribe waits for the broker's SUBACK before it returns. Several subscriptions can share a filter; the broker holds one subscription for it, at the highest QoS any of them asked for. A message published after it returns is received, which matters for request and response protocols. The subscription lasts until the scope that created it closes.

Talk to a Bambu Lab printer

Bambu Lab printers in LAN mode run an MQTT broker on port 8883. The user name is bblp and the password is the printer's access code. examples/bambu-report.ts subscribes to a printer's reports and asks it for a full status report:

PRINTER_HOST=192.0.2.10 PRINTER_SERIAL=... PRINTER_ACCESS_CODE=... bun examples/bambu-report.ts

Connect options

| Option | Default | Meaning | | --- | --- | --- | | host | required | Broker host name or IP address. | | port | 8883 with TLS, 1883 without | Broker port. | | tls | off | true uses TLS with the runtime's CA store. An object passes through to tls.connect, for example { ca } or { rejectUnauthorized: false }. | | clientId | printhive- and 12 random hex digits | MQTT client identifier. | | username, password | none | Credentials. The password can be a string or bytes. | | cleanSession | true | With false, the broker keeps subscriptions and queued QoS 1 and 2 messages across reconnects, so an unfinished QoS 1 or 2 publish can finish after one. See Publish. | | keepAlive | 60 seconds | The client sends PINGREQ after three quarters of a period without writes, so a full period never passes silently, and drops a connection with no PINGRESP within one period. 0 turns it off. | | connectTimeout | 10 seconds | Time allowed for the socket and CONNACK. | | will | none | { topic, payload, qos, retain }, published by the broker if the client disappears without DISCONNECT. | | reconnect | exponential from 500 ms, capped at 30 s, forever | An Effect Schedule for reconnecting after an established connection drops. Its first delay comes before the first attempt. false closes the client on the first drop. | | maxPaused | off | How long one full subscription may keep the client paused before the client drops it. See Slow consumers. |

The first connection is not retried, so connect fails fast when the broker is unreachable or refuses the credentials. Reconnecting stops early on a refusal that retrying cannot fix, such as bad credentials.

Publish

client.publish(topic, payload, { qos, retain }) takes a string or a Uint8Array.

  • QoS 0 completes once the packet is written. While the client is reconnecting, or the socket's buffer is full, it waits.
  • QoS 1 completes on PUBACK, and QoS 2 on PUBCOMP.
  • When the connection drops mid-handshake, what happens after the reconnect depends on whether the broker kept the session (sessionPresent in CONNACK):
    • Kept, which needs cleanSession: false: the message is sent again with DUP set, and the publish completes as usual.
    • Not kept, as on every reconnect with the default cleanSession: true: the publish fails with DeliveryUnknown. The broker may already have delivered the message, and a broker without the session would deliver a resend a second time (section 3.1.2.4), so the client does not resend it. Retry only if a second delivery is safe, for example a command whose effect you can check first.
    • A QoS 1 or 2 publish made while disconnected was never written, so it is sent for the first time after the reconnect, either way.
  • A publish interrupted before its bytes reach a socket is never sent, at any QoS, so it is safe to retry. One interrupted after that still finishes its exchange, as MQTT requires.

Slow consumers

Each subscription holds up to bufferSize messages, 1024 by default:

const reports = yield* client.subscribe("device/+/report", { bufferSize: 64 })

When a subscription is full, the client stops reading from the socket. TCP then pushes back on the broker, which queues or drops messages according to its own limits. Reading resumes once every full subscription has drained to half. The client keeps sending PINGREQ while paused, so a slow consumer does not cost the connection. It cannot read the PINGRESP until it resumes, though. A dead host or network still fails those PINGREQ writes at the TCP level, but a broker that stops answering while keeping its TCP connection open is detected only once the consumer catches up and reading resumes. Messages already read when a buffer fills are kept, so a buffer can exceed bufferSize by one socket read's worth.

By default a consumer that never comes back keeps the client paused, and every other subscription waits with it. maxPaused puts a limit on that:

const client = yield* connect({ host, maxPaused: "30 seconds" })

A subscription that stays full for maxPaused is dropped. Its consumer gets the messages it already had, then its stream fails with SubscriptionStalled. The client unsubscribes if no other subscription uses the filter, and resumes reading for the rest. The limit counts how long the subscription has been full this time, so a consumer that stalls often but always catches up is never dropped. The check runs every quarter of maxPaused, so a drop can come up to a quarter late. Reading resumes after the drop, so this also limits how long a broker that stopped answering can go unnoticed: the PINGRESP deadline starts again then.

When only the newest messages matter, such as a printer's status reports, set overflow: "dropOldest":

const latest = yield* client.subscribe("device/+/report", { bufferSize: 1, overflow: "dropOldest" })

Such a subscription keeps the latest bufferSize unread messages and drops older ones. Its stream hands them out one at a time, so a consumer that falls behind resumes at the newest messages rather than a stale batch. It never pauses the client, so other subscriptions keep flowing. The client acknowledges a QoS 1 or 2 message when it arrives, before the queue can drop it, and a broker that receives that acknowledgement does not resend the message. If the connection drops before the acknowledgement reaches the broker, a persistent session (cleanSession: false) may deliver it again.

Connection status

client.status reads the current ConnectionStatus, and client.statusChanges is a stream of it. The status is one of:

  • Connecting
  • Connected, with sessionPresent
  • Reconnecting, with attempt and the error that caused it
  • Closed, with the final error

Once the client is Closed, every subscription stream fails with the error that closed it.

Errors

Every error is a tagged error, so Effect.catchTag can handle each one.

| Error | Cause | | --- | --- | | ConnectionError | The socket failed, timed out, or closed, or keep-alive expired. | | ConnectionRefused | The broker refused CONNECT. returnCode holds its reason (section 3.2.2.3). | | SubscribeRejected | The broker answered SUBSCRIBE with 0x80 for the filter. | | SubscriptionStalled | A "backpressure" subscription stayed full past maxPaused, so the client dropped it. | | DeliveryUnknown | A QoS 1 or 2 publish was cut off by a dropped connection, and the broker came back without the session, so it may or may not have been delivered. | | InvalidTopic | A topic has wildcards, or a filter misplaces # or +. | | InvalidOption | An option is out of range, such as a bufferSize below 1, an unknown overflow, or a maxPaused that is not positive. | | MalformedPacket | The broker sent bytes that are not valid MQTT 3.1.1. | | ProtocolError | The broker sent a packet a client must not receive. | | ClientClosed | The client's scope closed, or reconnecting gave up. |

Run a server for tests and emulators

@printhive/mqtt/server runs the broker side in-process, so a test or an emulator can talk to the real client over real sockets. It is not a general-purpose broker: it doesn't route between clients or keep retained messages.

import { Effect, Stream } from "effect"
import { serve } from "@printhive/mqtt/server"

const program = Effect.gen(function* () {
  const server = yield* serve({
    tls: { key, cert },
    authenticate: (connect) => Effect.succeed(connect.username === "bblp" ? 0 : 5)
  })

  yield* Stream.runForEach(server.sessions, (session) =>
    session.inbound.pipe(
      Stream.runForEach((packet) =>
        packet._tag === "Publish" ? Effect.asVoid(session.publish("device/X/report", '{"print":{}}')) : Effect.void
      ),
      Effect.forkScoped
    )
  )
})

The server answers PINGREQ, UNSUBSCRIBE and the QoS 1 and 2 handshakes itself. SUBSCRIBE goes to onSubscribe, which chooses the SUBACK codes. The SUBACK waits for that Effect, so a test can stall it by sleeping, drop it with Effect.never, or refuse a filter with 0x80, while other packets keep flowing. Every packet also appears on the session's inbound, in order.

Faults are Effects the test writes:

  • write(packet) sends any packet, for example a SUBACK with the wrong packet id.
  • writeRaw(bytes) sends malformed bytes.
  • mute(true) drops every write, PINGRESP included, like a printer that has gone silent.
  • close("end" | "half-close" | "destroy") ends the connection three ways.

With keepAlive: "ignore", the server never drops a silent client, which models a half-open socket.

Sessions are buffered from the moment the server starts, and each session buffers up to bufferSize packets before the server stops reading its socket. As on the client, a paused session answers nothing, PINGREQ included, until its consumer catches up. The server closes with its scope, or earlier with server.close({ force }).

Packets, the codec, and tests

@printhive/mqtt/packet exports the MQTT 3.1.1 packet types and their constructors. @printhive/mqtt/codec exports encode, the incremental Decoder, and MalformedPacket. Tools that record or replay traffic can use them without opening a connection.

Every timer runs on Effect's Clock: keep-alive, the connect timeout, and the reconnect schedule. Under TestClock from effect/testing/TestClock, TestClock.adjust drives PINGREQ, the PINGRESP deadline, and reconnect delays without real waiting. Socket I/O still takes real time.

Performance

The decoder reads packets straight out of the socket chunks it is given. Each payload is a view into the chunk, not a copy. Small outgoing packets are sliced from a shared slab, and bursts of writes are corked into one syscall.

bench/RESULTS.md has the method, every range, and the limits. Summary, median of 5 alternating runs on an Apple M3 Pro:

| | Bun | Node.js | | --- | --- | --- | | Decode, vs mqtt-packet | 3.9x | 4.4x | | Encode, vs mqtt-packet | 1.5x | 3.2x | | End to end QoS 0, 64 B, vs mqtt.js | 1.47x | 1.73x | | End to end QoS 0, 1 KB, vs mqtt.js | 1.23x | 1.68x | | End to end QoS 1, 1 KB, vs mqtt.js | no measurable difference | no measurable difference |

The end-to-end QoS 0 runs are limited by Mosquitto, which used a full core while this client used about two thirds of one.

Effect's tagged constructors and Match measured 4 to 6 times slower than plain objects with a switch. So src/packet.ts, src/codec.ts, and src/session.ts keep plain tagged objects, and the lint configuration exempts only those files from three Effect rules.

Limits

  • MQTT 3.1.1 only. MQTT 5 is planned.
  • Backpressure pauses the whole connection, so one slow subscription delays every subscription on that client. Give a slow consumer its own client when the others must keep up.
  • With overlapping subscriptions, a broker may send a message once per matching filter. Each copy reaches every local stream whose filter matches.

Develop

bun install
bun run check       # oxlint with the anti-slop rules, tsc, and the tests on Bun
bun run test:node   # the same tests on Node.js through Vitest
bun run build

The tests run against a real broker, aedes, and against scripted brokers built on the codec. They never mock modules.

Lint runs oxlint with the anti-slop rules, including its Effect rules. They are vendored in tools/oxlint/anti-slop/, and UPSTREAM.md there records the source commit.

To run the benchmarks, start Mosquitto, then run them:

docker run -d --name mqtt-bench -p 18830:1883 -v $PWD/bench/mosquitto.conf:/mosquitto/config/mosquitto.conf:ro eclipse-mosquitto:2
bun bench/run.ts
bun bench/codec.ts && node bench/codec.ts

CI runs the checks on Bun, and the tests on Node.js 22, 24, and 26, all on Blacksmith runners. To release, set the version and push its tag. The release workflow publishes to npm with provenance.

npm version patch
git push --follow-tags

License

MIT