Work in progress. This guide is being built up incrementally. Sections are added as APIs stabilize.
This is the top-level migration guide for moving code from the v2 client (nats.java) to v3 (nats.java.v3). The v3 client is reorganized into separate projects: core, jetstream, kv, os, and service. Migration topics are grouped by project.
Two topics are large enough to have their own documents, both linked again from the section they belong to:
- MIGRATION_GUIDE_OPTIONS.md — the
Optionsconstants and property keys. - MIGRATION_GUIDE_NKEY.md — NKeys, which left the client for their own library and now require you to choose and configure an
NKeyProvider.
v3 requires nats-server 2.10 or later, and 2.14 or later is preferred. v2 supported older servers and carried the machinery to prove it: runtime version gates, client-side errors for "this server is too old for that", and opt-outs to force the legacy path. v3 assumes the 2.10 floor instead of testing for it, so that machinery is gone:
| v2 | v3 |
|---|---|
JsConsumerCreate290NotAvailable (CON-90301) |
(deleted — the 2.9.0 consumer-create API is always present at the 2.10 floor) |
JsMultipleFilterSubjects210NotAvailable (CON-90303) |
(deleted — multiple filter subjects are always available at the 2.10 floor) |
Nothing replaces them, because at 2.10+ neither condition can occur. If you point v3 at a pre-2.10 server it is unsupported, and the failure will not be diagnosed for you — you will get whatever the server returns for an API it does not have, not a clear "server too old" error. Check your servers before migrating.
This applies only to the floor. Features introduced after 2.10 are still detected at runtime from the server's INFO and degrade gracefully — for example the 2.11 direct batch get.
Work in progress. This section tracks the v3 exception rework as it lands. Re-read it when you take a new v3 build. It has two parts: the reclassifications (usage errors that were
IOExceptionare now unchecked — first), and theJetStreamExceptionconsolidation (theIOException+JetStreamApiExceptionpair on the JetStream surface collapses to one base type — second).
v3 is correcting a long-standing v2 habit: throwing a checked IOException for things that were never I/O problems. In v2 several client-side validation failures — misuse the API and you get an exception — were reported as IOException purely because the surrounding method already declared it and changing the signature would have been a breaking change. v3 is the major version where that constraint is lifted, so those cases now throw the unchecked exception that actually fits (IllegalStateException for calling something at the wrong time, IllegalArgumentException for a bad argument). These are programming errors — you fix them by changing your code, not by catching them at runtime — so forcing a catch was never the right shape.
Two things change, and they migrate very differently.
1. Calls that no longer declare IOException at all — the compiler will find these for you. Constructing a JetStream context does not talk to the server, so it can no longer fail with an IOException; the constructors and factories dropped it:
| Affected | v2 | v3 |
|---|---|---|
new JetStream(nc) / JetStream.instance(nc) |
throws IOException |
(no checked exception) |
new JetStreamManagement(nc) / .instance(nc) |
throws IOException |
(no checked exception) |
new KeyValueManagement(nc) / new ObjectStoreManagement(nc) |
throws IOException |
(no checked exception) |
new ObjectStore(...) / osm.objectStore(name) |
throws IOException |
(no checked exception) |
If your v2 code wrapped one of these in try { … } catch (IOException e), it will now fail to compile — error: exception IOException is never thrown in body of corresponding try statement. That is the safe kind of break: the compiler points at every site and you delete the dead catch. (The "connection is closing/closed" guard these had still fires — it is now an IllegalStateException, unchecked, which you should not normally catch.)
One asymmetry to expect: getting a KV bucket still throws, getting an OS bucket does not. KeyValueManagement.keyValue(name) (and the KeyValue constructor) still declare throws IOException because they verify the backing stream exists (getStreamInfo) at creation time — a real server round-trip. ObjectStore does no such check at construction, so it dropped the exception. This is not an oversight; it reflects that only one of the two actually contacts the server when you open the bucket.
2. Calls that still declare IOException but no longer route every failure through it — the compiler will NOT warn you. This is the dangerous case. ConsumerContext.next() / fetch() / iterate() / consume() still throw IOException (a real request over the wire genuinely can), so a catch (IOException) around them still compiles cleanly — but two client-side checks that used to land in that catch now throw unchecked IllegalStateException and sail straight past it:
Now IllegalStateException (was IOException) |
When |
|---|---|
"The ordered consumer is already receiving messages…" |
you start a next/fetch/iterate/consume on an ordered consumer while a previous one is still running |
"Pinned not allowed with Next/Fetch" |
you call next/fetch on a pinned-client consumer |
So if you have v2 code shaped like this:
try {
Message m = consumerContext.next(1000L);
// …
} catch (IOException e) {
// in v2 this ALSO caught "already receiving" / "pinned not allowed"
handleProblem(e);
}it still compiles under v3, but those two conditions now escape as IllegalStateException and reach whatever is above you — often an uncaught crash. There is no compiler error to lead you here, so grep your codebase for catch blocks around consumer next/fetch/iterate/consume and around JetStream/KV/OS context creation, and check whether you were relying on IOException to catch a usage error. If you were, either fix the misuse (the right answer — these fire only when the calling code is wrong) or add a catch (IllegalStateException e).
This is the change the reclassifications above were clearing the way for. On the JetStream surface, the v2 signature pair throws IOException, JetStreamApiException becomes a single throws JetStreamException — plus throws InterruptedException, which v2 hid by reboxing it as IOException. So a JetStream call that read throws IOException, JetStreamApiException in v2 reads throws JetStreamException, InterruptedException in v3:
// v2
public StreamInfo getStreamInfo(String streamName) throws IOException, JetStreamApiException
// v3
public StreamInfo getStreamInfo(String streamName) throws JetStreamException, InterruptedExceptionTwo exceptions, both of which are true — replacing two, one of which (IOException) never actually happened on this surface. Every synthetic IOException the JetStream layer used to throw (a timeout, a status error, a bad ack, a rewrapped interrupt) is now thrown as the type that fits, all under the JetStreamException base.
What to catch. Catch the base JetStreamException and, if you need to tell the failures apart, switch on the subtype (Java 21 pattern-matching switch, no instanceof ladder):
try {
js.publish(subject, data);
}
catch (JetStreamException e) {
switch (e) {
case JetStreamApiException api -> report(api.getError()); // server returned an error
case JetStreamTimeoutException t -> retry(); // no response in time
case JetStreamProtocolException p -> fail(p); // malformed reply
default -> fail(e); // required — the base is not sealed
}
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
// abandon or retry
}The default is not optional and not a wart: JetStreamException is deliberately not sealed, so a future v3 build can add a subtype without breaking your switch. That is the whole reason it isn't sealed — additive, non-breaking evolution of the failure taxonomy.
The subtypes:
| Type | Package | Means | Key accessor |
|---|---|---|---|
JetStreamException |
io.nats.v3.client.api |
base — catch this | — |
JetStreamApiException |
io.nats.v3.client.impl |
the server returned an Error (JetStream API error) |
getError() |
JetStreamTimeoutException |
io.nats.v3.client.api |
no response within the request timeout | — |
JetStreamProtocolException |
io.nats.v3.client.api |
malformed response (the v2 "Invalid JetStream ack" cases) | — |
JetStreamApiException is unchanged as the runtime type for server-side API errors — if your v2 code already did catch (JetStreamApiException), it still catches exactly the same failures. It is now also a JetStreamException, so you can widen to the base and drop the separate IOException catch in the same edit. (The .impl-package subtypes are slated to move to .api in a later v3 build; catching the base JetStreamException — which is already in .api — insulates you from that move entirely.)
Status messages are a separate, unchecked family — not part of JetStreamException.
An unexpected status cannot be checked where it is raised: JetStreamSubscription.nextMessage* implements the core Subscription declarations, which carry no checked exception, and the legacy iterate raises from Iterator.hasNext(). So status errors are unchecked and sit in their own two-type hierarchy:
| Type | Package | Means | Key accessor |
|---|---|---|---|
StatusException |
io.nats.v3.client.impl |
a status message the client could not process — core raises it for a 503 on a plain request |
getStatus() |
JetStreamStatusException |
io.nats.v3.client.impl |
the same, raised by JetStream, carrying the note and the subscription | getStatus(), getNote(), getSubscription() |
JetStreamStatusException extends StatusException, so catch (StatusException) covers core and JetStream alike and catch (JetStreamStatusException) narrows to JetStream. Both are unchecked, so the compiler will not remind you — the javadoc @throws on every method that can raise one is the reminder.
Two rename notes, only relevant if you referenced these types by name:
JetStreamStatusCheckedExceptionis gone, with no checked replacement. If you caught it, catchJetStreamStatusExceptioninstead and note that nothing forces you to.- The v2
JetStreamStatusExceptionwas unchecked, and so is v3's. The name means the same thing it did in v2; what changed is its parent (StatusExceptionrather thanIllegalStateExceptiondirectly) and that it now carries the subscription.
The one place IOException survives — and it is real. ObjectStore.put(...) and ObjectStore.get(...) still declare throws IOException alongside JetStreamException, because they read and write your InputStream / OutputStream. That IOException means a stream failure on your side, not a NATS failure — keep the catch (IOException) there. It is the only spot on the JetStream surface where IOException is not a lie.
-
Options constants — user-facing changes — the
Optionsclass was split intoOptionsConstantsandOptionsProperties. Constants renamed to camelCase. May be folded into this guide later. -
NKeys — user guide and migration —
io.nats.client.NKeyis gone. NKeys now live in their own library,nkeys.java, asio.nats.nkey.NKey, and the API is provider-based: every static factory becomes an instance method on anNKeyProvideryou obtain fromNKeyProvider.getProvider(), so the Ed25519 implementation is yours to pick — one of the three shipped providers (stock BouncyCastle, the LTS build, or the FIPS build), or your own subclass if you cannot depend on BouncyCastle at all.v2 v3 NKey.createUser(random)NKeyProvider.getProvider().createUser()NKey.fromSeed(seed)NKeyProvider.getProvider().fromSeed(seed)NKey.TypeNKeyTypeNKey.isValidPublicUserKey(k)NKeyUtils.isValidPublicUserKey(k)(throws now — it no longer returnsfalse)jnats3-coredoes not bring a provider implementation and there is no default. If you use nkey or creds-file authentication — including throughNats.credentials(...)/Nats.staticCredentials(...), whose signatures did not change — you must add a provider artifact and name it via theNKEY_PROVIDER_CLASSenvironment variable or thenkey.provider.classsystem property. Neither step is something the compiler can remind you about: the code builds and then throws on the first signature. The guide covers the setup, the full API mapping, the behavior traps, and Claude Code prompts for both halves of the job. -
TLS: hostname verification is on by default, and
opentlsis gone. Details in TLS configuration.- The certificate a server presents must be issued for the server name the connection was made with: the configured hostname, in every
HostnameResolveMode, or the ip address when the server is configured by ip address, in which case the certificate must carry that address as a subject alternative name. A server discovered as a bare ip address is checked against the hostname of the server that announced it.tlsVerifyHostname(false)or thetlsVerifyHostname=falseproperty turns the check off. - Options that use TLS reject a
ws://server in the server list atbuild(), becausews://is never upgraded to TLS. Usewss://. - A
ws://server that arrives later, fromconnect_urlsor a customServerPool, is skipped without being dialed and reported through the newErrorListener.serverRejected(conn, server, reason).ServerPoolhas a new abstract method,serverRejected(NatsUri), andacceptDiscoveredUrls(List)is replaced byacceptDiscoveredUrls(List, NatsUri origin), where the origin is the server whose INFO supplied the list, or null; a custom pool implements both. - The configured hostname is now sent as the TLS server name (SNI) in every
HostnameResolveMode, including single label names, andHostnameResolveMode.Unresolvedconnects without a proxy. - The
opentls://scheme,OptionsBuilder.openTls()/openTls(boolean), theopenTlsproperty andSSLUtils.createOpenTLSContext()are removed. Anopentls://url now fails with "Unsupported NATS URI scheme." To trust any certificate, which is insecure, supply the context:sslContext(SSLUtils.createTrustAllTlsContext()). The hostname is still verified with that context, so a certificate that does not name the server also needstlsVerifyHostname(false).
- The certificate a server presents must be issued for the server name the connection was made with: the configured hostname, in every
-
Connectioninterface is gone — useNatsConnectiondirectly. The v2io.nats.client.Connectioninterface is removed. There is now exactly one connection type,io.nats.v3.client.impl.NatsConnection. It is created from theNatsImplclass (or, more commonly, via theNats.connect(...)static factory which now returnsNatsConnectioninstead ofConnection).v2 v3 Connection nc = Nats.connect();NatsConnection nc = Nats.connect();Connection nc = Nats.connect(options);NatsConnection nc = Nats.connect(options);Connection nc = Nats.connect(url);NatsConnection nc = Nats.connect(url);Anywhere a method previously returned
Connection, it now returnsNatsConnection. Anywhere you acceptedConnectionas a parameter, switch toNatsConnection. -
Consumerinterface is gone. The v2io.nats.client.Consumerinterface — the shared supertype ofSubscriptionandDispatcherthat carried the pending-limit, pending/dropped/delivered counts, anddrainmethods — is removed, with no public replacement supertype. In practice it was almost never referenced by name (it only ever showed up as a supertype), so most code needs no change: every method it declared still exists, now declared directly onSubscription/NatsSubscription(synchronous) and onDispatcher(asynchronous). The confusing "consumer" concept — the thing that owns a pending queue and can become a "slow consumer" — was renamed internally toNatsMessageSink, a more useful name for what it actually is (a sink messages drain into); that class is impl-only and never appears in the public API.v2 v3 Consumerused as a typeuse Subscription/NatsSubscriptionorDispatcherdirectlyslowConsumerDetected(Connection, Consumer)slowConsumerDetected(NatsConnection, Subscription)Consumer.DEFAULT_MAX_MESSAGES/Consumer.DEFAULT_MAX_BYTESOptionsConstants.DEFAULT_MAX_MESSAGES/OptionsConstants.DEFAULT_MAX_BYTESOne behavior change to note on the slow-consumer callback: for a dispatched (async) subscription, v2 handed you the
Dispatcher; v3 always hands you theSubscriptionwhose message hit the full queue — more useful, since the subscription names the subject. -
Removed connect-option behavior. Both the property constants and the corresponding
OptionsBuildersetters are gone. Any code that referenced these must be removed; there is no replacement.Removed constant Removed OptionsBuildersetter(s)Reason PROP_TIME_TRACE_LOGGERtimeTraceLogger(TimeTraceLogger),traceConnection()Feature removed (the TimeTraceLoggerinterface is also gone)PROP_REPORT_NO_RESPONDERSreportNoResponders()Client always reports No Responders -
OptionsBuilder.userInfo(String, String)removed. TheString-typed overload is gone — Strings live on the heap until GC and can't be securely cleared. Use the existingchar[]overload instead:v2 v3 builder.userInfo("user", "password")builder.userInfo("user".toCharArray(), "password".toCharArray())The
char[]overload was already present in v2; only theStringoverload is retired in v3. Token-based authentication (token,tokenSupplier), keystore passwords, and the property-file path were alreadychar[]-based — no other credential setters change. -
OptionsBuilder.inboxPrefix(null)/inboxPrefix("")no longer throw. v2's setter would NPE on null (it dereferenced the argument to check for a trailing"."). v3 treats null / empty as "re-default atbuild()time" — the resultingOptionscarriesDEFAULT_INBOX_PREFIX. Code that accidentally passed null now silently gets sensible behavior; code that deliberately passed null was broken in v2 anyway. Non-null, non-empty prefixes behave as before (with"."appended if missing). -
OptionsBuilder.noHeaders()/noNoResponders()setters and their properties are gone. v3 always advertises both headers and no-responders support in itsCONNECTpayload — every NATS server v3 supports has those features unconditionally, so the toggles were no-ops in practice (the values were hard-coded in the connect string). Migration:v2 / removed in v3 v3 builder.noHeaders()(delete) builder.noNoResponders()(delete) options.isNoHeaders()(delete; treat as always false)options.isNoNoResponders()(delete; treat as always false)io.nats.client.noHeadersproperty(delete; silently ignored if left in a properties file) io.nats.client.noNoRespondersproperty(delete; silently ignored if left in a properties file) -
Reconnect-delay configuration moves from
Durationtolongmilliseconds. The three reconnect timing values use primitivelongms everywhere — fewer allocations on the reconnect path, no null-handling, and the unit (milliseconds) is documented in the javadoc. Property files need no change for these keys (PROP_RECONNECT_WAIT,PROP_RECONNECT_JITTER,PROP_RECONNECT_JITTER_TLS): the loader accepts either a plain integer of milliseconds (e.g.2000) or the ISO-8601 duration form (e.g.PT2S), converted to whole milliseconds. Negative values continue to be silently ignored (the default survives), matching the pre-existing v2 behavior.v2 / today v3 builder.reconnectWait(Duration.ofSeconds(2))builder.reconnectWait(2000)builder.reconnectJitter(Duration.ofMillis(100))builder.reconnectJitter(100)builder.reconnectJitterTls(Duration.ofSeconds(1))builder.reconnectJitterTls(1000)options.getReconnectWait()(returnsDuration)options.getReconnectWait()(returnslong)options.getReconnectJitter()options.getReconnectJitter()options.getReconnectJitterTls()options.getReconnectJitterTls()DEFAULT_RECONNECT_WAIT(Duration)DEFAULT_RECONNECT_WAIT(long)DEFAULT_RECONNECT_JITTERDEFAULT_RECONNECT_JITTERDEFAULT_RECONNECT_JITTER_TLSDEFAULT_RECONNECT_JITTER_TLSNo
Durationconvenience overloads on the setters — pass along. The other connection timing options (connectionTimeout,socketWriteTimeout,pingInterval,requestCleanupInterval,writeQueuePushTimeout) made the same move — see MIGRATION_GUIDE_OPTIONS.md §7. -
ReconnectDelayHandlersignature change. The single abstract method goes fromDuration getWaitTime(long totalTries)tolong getWaitTimeMillis(long round, Options options, boolean secure, boolean lameDuckTriggered). The interface stays single-abstract-method so lambda handlers continue to work. The handler is now stateless — the connection tracks the lame-duck signal itself and passes it in as the fourth argument. A new statelessDefaultReconnectDelayHandler.INSTANCEsingleton is whatOptions.getReconnectDelayHandler()returns when the user hasn't supplied a custom handler, and it's safe to share across many connections.ReconnectDelayBehaviorkeeps v2'sBeforeSubsequentRoundsdefault, so failover latency is unchanged.BeforeAllRoundsadditionally delays before the first round, which spreads a reconnect storm when one server drops a large client population at once; the newLameDuckAwaredoes that only when the server signalled LDM. The behavior governs whether the handler is invoked before round 1 at all, and applies to custom handlers as well as the default one.v2 / today v3 l -> Duration.ofSeconds(l * 2)(round, opts, secure, ld) -> round * 2000options.getReconnectDelayHandler() // may be nullnever null; defaults to DefaultReconnectDelayHandler.INSTANCE -
Runtime method timeouts move from
Durationtolong/Longmilliseconds. Every "how long do I wait" timeout on the runtime API — not just theOptionsconfig covered above — is now a primitive millisecond value: no per-call allocation, nonull-Durationhandling, unit documented in the javadoc. TheDurationoverloads are dropped (the lone exception isnakWithDelay, which keeps aDurationconvenience overload for expressing seconds/minutes). Methods that read/consume a message take a nullable@Nullable Longsonullcan still carry the meaning the oldnull-Durationhad; every other timeout takes a plainlong. The catch when porting is the sentinels — a0or negative value can silently change behavior:v2 v3 sentinel for 0/ negative /nullsub.nextMessage(Duration.ofSeconds(1))sub.nextMessage(1000L)@Nullable Long:null= poll once / return immediately,<= 0= wait forever,> 0= wait that longnc.request(subj, data, Duration.ofSeconds(2))nc.request(subj, data, 2000)<= 0= use the default (blocks for the connection timeout)nc.requestAsync(subj, data, Duration.ofSeconds(2))nc.requestAsync(subj, data, 2000)<= 0= use the default (future swept at the request-cleanup interval)nc.flush(Duration.ofSeconds(5))nc.flush(5000)<= 0= wait foreverconsumer.drain(Duration.ofSeconds(10))consumer.drain(10000)<= 0= wait forevermsg.ackSync(Duration.ofSeconds(2))msg.ackSync(2000)must be > 0msg.nakWithDelay(Duration.ofSeconds(5))msg.nakWithDelay(5000)or keepmsg.nakWithDelay(Duration.ofSeconds(5))Durationoverload retained for conveniencectx.next(Duration.ofSeconds(1))ctx.next(1000L)@Nullable Long:null/<= 0→ default expiry; a positive value must be>= MIN_EXPIRES_MILLSsub.fetch(100, Duration.ofSeconds(1))sub.fetch(100, 1000L)@Nullable Long:null/<= 0throws — a positive max-wait is requiredsub.iterate(100, Duration.ofSeconds(1))sub.iterate(100, 1000L)same as fetch— positive requiredThe most common gotcha is
nextMessage. v3 mapsnull= poll once and<= 0= wait forever. If you used a v2 idiom that passed a negative/zeroDurationto mean "return immediately," passnullnow — not0L, which now waits forever. The reading methods are boxed (Long) specifically sonullsurvives; the non-reading ones (request,requestAsync,flush,drain,ackSync) are plainlongand have nonullform. -
NatsDispatcher.internalStartrenamed tostartImpl. Visibility and signature are unchanged —protected void startImpl(String id, boolean threaded)— only the name. This affects one kind of code: a subclass ofNatsDispatcherdeclared in the client's impl package that drives the message drain loop itself instead of letting the dispatcher start its own thread. The known case isnats-java-vertx-client'sVertxDispatcher, which calls it withthreaded = falseso messages are delivered on the Vert.x event loop. If you subclassNatsDispatcher, rename the call; nothing else changes.v2 v3 internalStart(id, false)startImpl(id, false) -
Connection.RTT()returnslongnanoseconds, gained a timeout overload, and no longer reports every failure asIOException. The name is unchanged.v2 v3 Duration RTT() throws IOExceptionlong RTT() throws IOException, TimeoutException, InterruptedException(none) long RTT(long timeoutMillis) throws IOException, TimeoutException, InterruptedExceptionThe return is nanoseconds, and nothing at the call site says so —
Durationwas self-describing, a barelongis not. This is the trap:if (nc.RTT().toMillis() < 50)becomesif (nc.RTT() < 50), which compiles and means 50 nanoseconds. Convert at the call site (nc.RTT() / 1_000_000for millis) or compare against a nanosecond literal. The new overload'stimeoutMillisparameter is milliseconds, matching every other timeout in v3 — the wait is bounded in millis, the measurement is returned in nanos, because a round trip is routinely sub-millisecond.Four failures used to arrive as one
IOExceptionnaming only the last of them. They are now distinct, and this is the safe kind of break — the return type changed, so the compiler stops at every call site rather than letting a behavior change through silently:condition v2 v3 not connected IOExceptionIllegalStateException(a usage error — see Exceptions above)max outgoing pings exceeded (not checked — v2 bypassed the guard) IllegalStateExceptionserver did not respond in time IOExceptionwrappingTimeoutExceptionTimeoutExceptionconnection closed mid-call CancellationExceptionescaped uncaughtIOExceptionthread interrupted IOException(interrupt flag set, but uncatchable as an interrupt)InterruptedExceptionThree of those were bugs, not just poor typing: v2 left its pong future in the queue on timeout (so the next PONG completed a dead future and a live
flush()lost its turn), skipped themaxPingsOutbound entirely, and let aCancellationExceptionescape a method declaredthrows IOExceptionwhenever the connection dropped mid-call. -
Nats.connectReconnectOnConnectis renamedNats.connectReconnectOnFailure. All four overloads (no argument,String url,String url, AuthHandler handler,Options options) keep their parameters and behavior: if the initial connect fails on every server, the connection runs the reconnect logic instead of throwing. Thebooleanparameter ofNats.connectAsynchronouslyis renamedreconnectOnInitialFailure; its meaning is unchanged.v2 v3 Nats.connectReconnectOnConnect(...)Nats.connectReconnectOnFailure(...)
See jetstream/README.md for the project overview.
In v2 you obtained these from the Connection interface:
JetStream js = nc.jetStream();
JetStream js = nc.jetStream(jsOptions);
JetStreamManagement jsm = nc.jetStreamManagement();
JetStreamManagement jsm = nc.jetStreamManagement(jsOptions);In v3, those overloads are removed from NatsConnection. Construct them directly with their public constructors:
JetStream js = new JetStream(nc);
JetStream js = new JetStream(nc, jsOptions);
JetStreamManagement jsm = new JetStreamManagement(nc);
JetStreamManagement jsm = new JetStreamManagement(nc, jsOptions);(Both classes live in io.nats.v3.client.impl. Static instance(...) factories also exist on JetStream if you prefer that style.)
JetStream does not have the subscribe methods. Every pushSubscribe overload is in JetStreamPushSubscribe and every pullSubscribe overload is in JetStreamPullSubscribe, both in io.nats.v3.client.impl, with the same parameters. Call them as static methods with the JetStream context as the first parameter, or make an instance from the context:
JetStreamPushSubscription sub = JetStreamPushSubscribe.pushSubscribe(js, stream, consumerName);
JetStreamPullSubscribe pull = new JetStreamPullSubscribe(js);
JetStreamPullSubscription sub = pull.pullSubscribe(stream, new PullConsumerCreator());The simplified consumers (getStreamContext, createConsumer, getConsumerContext) stay on JetStream, and they are the preferred way to consume; JetStreamPushSubscribe and JetStreamPullSubscribe exist only to support the legacy behavior. See Consuming from JetStream.
JetStreamPullSubscription keeps only the primitive pull methods (pull, pullNoWait, pullExpiresIn). fetch, iterate, reader and the JetStreamReader interface are in the separate Legacy JetStream module, artifact jnats3-ljs, as JetStreamLegacyPull in io.nats.v3.client.impl. They behave as before. Call them as static methods with the subscription as the first parameter, or make an instance from the subscription:
List<Message> messages = JetStreamLegacyPull.fetch(sub, 10, 1000);
Iterator<Message> iterator = new JetStreamLegacyPull(sub).iterate(10, 1000);
JetStreamReader reader = JetStreamLegacyPull.reader(sub, 500, 125);JetStreamSubscription.MIN_EXPIRE_MILLIS moved with them, to JetStreamLegacyPull.MIN_EXPIRE_MILLIS.
For new code use the simplified API instead:
| v2 | v3 simplified API |
|---|---|
sub.fetch(batch, maxWait) |
consumerContext.fetch(FetchConsumeOptions) / fetchMessages(int) / fetchBytes(int) → FetchMessageConsumer |
sub.iterate(batch, maxWait) |
consumerContext.iterate() / iterate(ConsumeOptions) → IterableMessageConsumer |
sub.reader(batch, repullAt) |
consumerContext.iterate(...) for an endless iterator, or consume(...) for a handler |
New in v3, and there purely to remove a choice that was easy to get wrong. NatsConnection has had two createDispatcher overloads since v2 — one that takes a default MessageHandler and one that takes nothing — and for JetStream the no-argument one is almost always the right call, because a JetStream subscription carries its own handler per subscription rather than leaning on the dispatcher's default. Having it on JetStream makes that obvious at the call site:
// v2, and still valid in v3 - but you have to know which overload JetStream wants
Dispatcher d = nc.createDispatcher();
// v3, says what it is for
NatsDispatcher d = js.createDispatcher();It is a convenience, not a new capability — the body is conn.createDispatcher(null) — so nothing breaks if you keep calling the connection. Supply the handler on the SubscribeBehavior alongside the dispatcher:
NatsDispatcher d = js.createDispatcher();
SubscribeBehavior behavior = new SubscribeBehavior()
.dispatcher(d)
.handler(msg -> handle(msg));
JetStreamPushSubscribe.pushSubscribe(js, stream, new PushConsumerCreator(), behavior);A dispatcher with no handler on either side cannot deliver anything, so that combination is rejected up front with an IllegalStateException — [SUB-90023] Dispatcher without a handler cannot receive messages. If you pass a dispatcher to SubscribeBehavior, pass a handler too.
The simplified-consumer interfaces and their Nats* implementations have been renamed to make their role explicit (they consume Messages):
v2 (io.nats.client / io.nats.client.impl) |
v3 (io.nats.v3.client.impl) |
|---|---|
IterableConsumer |
IterableMessageConsumer |
NatsIterableConsumer |
NatsIterableMessageConsumer |
FetchConsumer |
FetchMessageConsumer |
NatsFetchConsumer |
NatsFetchMessageConsumer |
These continue to extend MessageConsumer / NatsMessageConsumerBase as before — only the type names changed. Update imports and any explicit type declarations; behavior and method signatures are unchanged.
The JetStream request and publish-ack timeouts follow the same Duration → long ms move as the connection options — no allocation, no null-handling, unit (milliseconds) documented in the javadoc — and the Duration overloads are dropped.
| v2 / today | v3 |
|---|---|
JetStreamOptions.builder().requestTimeout(Duration.ofSeconds(5)) |
.requestTimeout(5000) |
jso.getRequestTimeout() (returns Duration) |
jso.getRequestTimeout() (returns long) |
featureOptionsBuilder.jsRequestTimeout(Duration.ofSeconds(5)) |
.jsRequestTimeout(5000) |
PublishOptions.builder().streamTimeout(Duration.ofSeconds(2)) |
.streamTimeout(2000L) (boxed Long — the L is required; .streamTimeout(null) resets to the default) |
po.getStreamTimeout() (returns Duration) |
po.getStreamTimeout() (returns long) |
PublishOptions.DEFAULT_TIMEOUT (Duration) |
PublishOptions.DEFAULT_TIMEOUT (long) |
Two behavior notes:
PublishOptionsproperty file needs no change.PROP_PUBLISH_TIMEOUTaccepts either a plain integer of milliseconds (e.g.1200000) or the ISO-8601 duration form (e.g.PT20M), converted to whole milliseconds — same loader as the connection-timeout properties (see MIGRATION_GUIDE_OPTIONS.md §7).JetStreamOptions.requestTimeout's "unset" sentinel. v2 usednullto mean "not set → fall back to the connection timeout." With a primitivelong, a value<= 0means the same thing — sorequestTimeout(0)(or never setting it) falls back to the connection timeout, exactly asnulldid.PublishOptions.streamTimeoutkeeps thenull-resets-to-default behavior. Unlike the other JetStream timeouts (primitivelong),streamTimeouttakes a@Nullable Long: passingnullresets the field toDEFAULT_TIMEOUT(reproducing the oldDuration-nullsemantics),0is a valid explicit value, and a negative throws. Because the parameter is a boxedLong, integer literals need theLsuffix —streamTimeout(2000L), notstreamTimeout(2000).
See kv/README.md for the project overview.
See os/README.md for the project overview.
See service/README.md for the project overview.
-
Service.isStarted(long, TimeUnit)is nowisStarted(long timeoutMillis), and it actually checks.v2 v3 boolean isStarted(long timeout, TimeUnit unit)boolean isStarted(long timeoutMillis)This is a behavior change, not just a signature change, and it is the one worth reading. In v2 the method waited on a future that
startService()completes synchronously before it returns — so it answered "hasstartService()been called", always immediately, and alwaystrueafterwards. It said nothing about whether the server had registered the service's subscriptions, which is what callers actually wanted to know. Code that started a service and then published to it could still lose the race, and did so most visibly on loaded machines.v3 confirms with a round trip on the service's connection. The server reads one connection's stream in order, so a completed round trip proves it has already processed every subscription
startService()queued before it. Afalsereturn now means something: not started, or not confirmable within the timeout.service.startService(); if (!service.isStarted(1000)) { // the server has not registered the endpoints - do not publish yet }
Two limits to know. Only subscriptions on the service's own connection are confirmed — an endpoint given its own
Dispatcherbuilt from a different connection is not covered. And the no-argumentisStarted()is unchanged: it remains the cheap local "hasstartService()been called" check, so do not reach for it when you mean readiness.