Hi all,
I wanted to give a heads-up that I'm starting work on a new Rust client,
meant to become an officially supported Apache Pulsar SDK. It will live under
the project, in apache/pulsar-client-rust, and be released through the ASF
process like the Go, C++, Python, Node.js and DotPulsar clients.
Today the project doesn't host a Rust client of its own. Scalable topics
require every SDK to implement a new client model, so this seemed like the
right point to start one.
In short: build it from scratch, around two things that didn't exist when
the current Rust client was written:
1. the Scalable Topics client specification (PIP-494, spec/scalable-topics/
in apache/pulsar), as the API and behavior contract;
2. a thread-per-core runtime model with completion-based I/O.
== Why now
Scalable topics (PIP-460 and its sub-PIPs 468, 483, 486) change the client
model a lot. Applications no longer see partitions. The client tracks a
segment layout through a DAG watch and routes keys itself. There are three
consumer types (Stream, Queue, Checkpoint), each with its own ordering and
ack contract, and consumer assignment is driven by a controller. With
PIP-494 we now have a language-neutral, normative spec of that contract,
with the Java V5 client as the reference implementation.
The spec says it is the source of truth, not any single implementation. The
best way to test that claim is a second implementation written from the spec
alone. Reading it closely for this work has already turned up two issues:
- conformance.md C2 gives the routing hash as `Murmur3_32 & 0xFFFF`. But
client-behavior.md §2, wire-protocol.md §5 and the Java SegmentRouter
all use the high 16 bits (`>>> 16`), with the low 16 bits reserved for
entry bucketing. A client built from the checklist would route keys
differently from every other client. This is an editorial fix, and I'll
send a PR.
- The spec requires serialized MessageId and Checkpoint values to be opaque
and restorable across versions, but it doesn't define their byte format.
Applications persist these values outside Pulsar, and mixed-language
deployments will want to pass them between SDKs. I'd propose writing the
Java V5 encoding (MessageIdV5 / CheckpointV5) into the spec through the
PIP-494 change process, and having the Rust client follow it from day one.
== Why a new codebase
The website currently lists streamnative/pulsar-rs as the Rust client. It is
actively maintained for the classic API and has served the community well.
I don't think it is the right base for this work, for structural reasons:
- Its runtime abstraction (the Executor trait) requires `Send` futures, and
the connection layer is built around it. That conflicts with the
thread-per-core model below.
- The V5 surface needs new core types. For example, a V5 MessageId carries
a per-segment position vector, while pulsar-rs exposes the raw protobuf
MessageIdData.
- Transactions, chunking and end-to-end encryption are not implemented yet.
Adapting it would amount to a rewrite, and it would break its existing users
along the way. So the plan is to start clean and borrow ideas where they
help. Once the official client is ready, we'll deprecate pulsar-rs in its
favor. I'd very much like the pulsar-rs maintainers to be part of this
effort.
== Runtime model
The client is built on compio, an async runtime with completion-based I/O:
io_uring on Linux, IOCP on Windows, and a polling backend elsewhere. Each
compio runtime is single-threaded.
- The core is a single-threaded client per event loop. All the state of a
producer or consumer lives on one loop: its per-segment producers or
consumers, connections, buffers and timers. Inside a loop there are no
locks, no atomics and no cross-thread wakeups.
- The spec requires the client, producers and consumers to be safe to use
from many threads (client-behavior.md §10). So the default public API is
a thread-safe layer on top. The client owns a small number N of loops,
and each producer or consumer is pinned to one loop when it is created.
Its handle is Send + Sync and forwards operations to that loop. The
futures it returns don't depend on any runtime, so applications can await
them from tokio, smol or a blocking wrapper. Nobody has to adopt compio to
use the client. The price of this layer is one channel hop per operation
between the caller's thread and the loop.
- The single-loop (!Send) API underneath is also public and first-class.
Applications that are thread-per-core themselves can embed the client in
their own compio runtime, with no hidden threads and no global state.
- The cost: each loop keeps its own connection pool, so a client can open up
to N connections to the same broker. With a small default N I think
that's acceptable, but it's worth discussing.
- io_uring is often blocked in containers by the default seccomp profiles.
The client will fall back to the polling driver, so it works out of the
box.
Logging uses `tracing`. Metrics are recorded through per-loop handles, so
recording costs no cross-thread synchronization, and are exported through
OpenTelemetry under the same metric names the Java client uses.
== API designed around the spec
The API maps each spec operation to idiomatic Rust, and uses the type system
to enforce what the spec says:
- Three consumer types, StreamConsumer, QueueConsumer and
CheckpointConsumer, each exposing only the ack model the spec allows:
cumulative ack only for Stream, individual ack and nack for Queue, and
for Checkpoint no ack at all, just a checkpoint() call that returns an
opaque, serializable Checkpoint.
- Segments never appear in the API. Layout tracking, key routing, the
retry when a segment goes away, per-segment fan-out, position vectors and
key-shared bucketing are all internal.
- Producers and consumers are long-lived and heal themselves after errors.
Close is an explicit, graceful `close().await`, because Rust has no async
drop. Dropping a handle still closes it on a best-effort basis.
- One Error type, whose kind() matches the spec's error categories.
NotFound, for example, is distinct from a generic failure.
- Producer<T> and consumers are typed by a schema.
- The API is async first, with a blocking module on top.
An illustrative sketch (the exact shape is up for discussion):
let client = PulsarClient::builder()
.service_url("pulsar://localhost:6650")
.build().await?;
let producer = client.new_producer(Schema::string())
.topic("topic://acme/orders/events")
.create().await?;
let id = producer.new_message().key("user-42").value("hello").send().await?;
let consumer = client.new_stream_consumer(Schema::string())
.topic("topic://acme/orders/events")
.subscription_name("billing")
.subscribe().await?;
let msg = consumer.receive().await?;
consumer.acknowledge_cumulative(msg.id()).await?;
== Scope and testing
The first goal is the spec's required core (C1-C15), including the
consumer-side key-shared bucketing that the Stream consumer needs, plus the
migration bridge so the client also works with existing persistent:// topics
(see below). Token and mTLS authentication come first, then OAuth2. The other
optional capabilities (transactions, namespace subscriptions, dead-letter,
encryption, chunking) will be added on top of that core.
For testing, the plan is to:
- port the scenarios (not the code) of the existing Java V5 tests, about
190 unit tests in pulsar-client-v5 and about 500 tests elsewhere, mostly
in pulsar-broker. They would run against a simulated broker for unit-level
cases, and against a broker container built from master for integration;
- share routing test vectors with Java, and add golden-byte tests so
MessageId and Checkpoint values round-trip between Rust and Java;
- possibly grow this into a cross-language conformance suite that every
SDK could run.
== Project setup
- The crate will be published as `apache-pulsar`. The name `pulsar` on
crates.io belongs to pulsar-rs, and reusing it would be confusing. Apache
Avro's official crate, `apache-avro`, is the precedent.
- The new client works with existing topics too, not only scalable ones.
Through the spec's migration bridge, a persistent:// topic, partitioned or
not, is produced to and consumed from with the same API, and keys keep
the same key-to-partition routing as v4 clients. That is also how
pulsar-rs users can move over before pulsar-rs is deprecated.
- The protocol core doesn't depend on any runtime ("sans-IO"). The codec,
request tracking and the producer and consumer protocol state are plain
code over bytes, driven by a thin compio layer. That makes deterministic
tests against a simulated broker easy, keeps the churn of a pre-1.0
compio contained to one layer, and leaves room for another driver later.
== Later phase: a base for other SDKs
Once the Rust SDK is proven, it could become the core that other language
clients wrap, possibly with a classic-API crate as well. The tooling for
building wrappers around Rust is much better than what we had when wrapping
the C++ client. This isn't part of the initial effort, but the design keeps
it possible.
== Next steps
Development will happen in the open in apache/pulsar-client-rust. In
parallel I'll send the C2 fix and a PIP to standardize the MessageId and
Checkpoint encoding.
Feedback on any of the above is very welcome. Contributors and testers are
welcome too, especially anyone who wants to try it against real workloads
early.
Thanks,
Matteo
--
Matteo Merli
<[email protected]>