A client is created from a KlokBrokerClientConfig, built either programmatically or from the environment.
KlokBrokerClientConfig config = KlokBrokerClientConfig.builder()
.serviceUrl("pulsar+ssl://broker.ipaas.se:6651")
.authUrl("https://auth.ipaas.se/auth/realms/klok")
.authClientId("acme-finance-egress")
.authClientSecret(secret)
.authAudience("pulsar") // default
.klokInstance("acme-egress-fortnox") // klok-instance property on every message
.routeId("ACME001E1_FortnoxOfframp") // metrics prefix, klok-route-id on consumers and producers
.klokDevUrl("https://klok.dev") // request links in the messages of a missing topic or grant
.build();
KlokBrokerClientConfig fromEnv = KlokBrokerClientConfig.buildFromEnv();
Environment variables
| Variable |
Builder |
Default |
KLOK_BROKER_SERVICE_URL |
serviceUrl |
pulsar+ssl://broker.ipaas.se:6651 (DEFAULT_SERVICE_URL), as in the wire contract, the Python and TypeScript clients and the Quarkus extension; up to 0.3.8 the Java client defaulted to https://broker.ipaas.se:8443 |
KLOK_BROKER_AUTH_URL |
authUrl |
https://auth.ipaas.se/auth/realms/klok |
KLOK_BROKER_AUTH_CLIENT_ID |
authClientId |
required; build() throws without it, also when a blank authUrl switches authentication off (the Quarkus extension then passes none) |
KLOK_BROKER_AUTH_CLIENT_SECRET |
authClientSecret |
required, as authClientId |
KLOK_BROKER_AUTH_AUDIENCE |
authAudience |
pulsar |
KLOK_BROKER_TLS_TRUST_CERTS_FILE_PATH |
tlsTrustCertsFilePath |
KLOK_CA_FILE_PATH, read when the Pulsar client is created, else the Klok Root CA bundled in the jar (klok-root-ca.cert.pem) |
KLOK_INSTANCE |
klokInstance |
none; KLOK_INSTANCE_NAME is read as its deprecated alias when KLOK_INSTANCE is unset (from 0.3.9) |
KLOK_ROUTE_ID |
routeId |
none |
KLOK_BROKER_LISTENER_THREADS |
listenerThreads |
20; the floor of the listener thread pool, grown by the subscriptions' concurrency (see Concurrency) |
KLOK_DEV_URL |
klokDevUrl |
https://klok.dev (KlokTopicProvisioning.DEFAULT_KLOK_DEV_URL, the wire contract's topics.provisioning.request.defaultBaseUrl); the base URL of the klok.dev request link in the messages of a missing topic or grant (see Missing topics and grants), from 0.3.10. A configuration built with the record's constructor and no URL reads KLOK_DEV_URL of the process when it renders a message |
The broker role a client authenticates as, which the messages of a missing grant name, is
service-account-<authClientId> (config.brokerRole()); a configuration without a client id names
service-account-<client id>.
TLS
A TLS connection (a pulsar+ssl:// or https:// service URL) trusts the CA file of the table above and verifies the
broker's host name: the certificate must name the host the client connects to, for the lookup and for every broker
connection. KlokPulsarClientManager sets enableTlsHostnameVerification(true) explicitly. That is a Klok rule, not a
library default (Pulsar 5.0.0 also turned it on by default in the Java client, Pulsar 4 had it off); the Python and
TypeScript clients set the same, and the broker certificates carry the advertised names. A broker whose certificate does
not name its host is refused. A pulsar:// connection, such as a local standalone, has no TLS.
The client is built on the shaded org.apache.pulsar:pulsar-client 5.0.0 and uses its classic API
(org.apache.pulsar.client.api, as with Pulsar 4), not the new v5 API; it uses none of the client's internal packages.
The shaded client still needs pulsar-client-admin-api at run time (for Schema.AVRO and the OAuth2 plugin) without
declaring it, so this library declares it as a runtime dependency.
Quarkus
In a Quarkus application these are the klok.broker.* keys of the extension (klok.broker.service.url,
klok.broker.auth.enabled, klok.broker.auth.url, klok.broker.auth.client-id, klok.broker.auth.client-secret,
klok.broker.auth.audience, klok.broker.tls-trust-certs-file-path, klok.broker.listener-threads), and MicroProfile
maps the environment variables above onto them. In Kubernetes the values come from the Vault env secret of the service.
KlokBrokerClientConfig.builder()...build() reads the same variables for every value the builder leaves unset, so
buildFromEnv() is the builder with nothing set.
Logging
The library logs through slf4j-api only. It brings no logging backend and no logging configuration: the jar contains
no logback.xml, and the POM has no logback dependency. The application picks the SLF4J provider (Quarkus brings its
own; a plain Java service adds, for example, logback-classic and its own logback.xml) and sets the levels. Without
any provider SLF4J 2 prints one warning and logs nothing.
The loggers worth tuning:
| Logger |
What it covers |
dev.klok.brokerclient |
this client: subscriptions, outcomes, dead letters, request/reply |
dev.klok.brokerclient.connection |
the KLOK_BROKER_CONNECTION lines of the connection watchdog; never lower it below WARN (see Connection health) |
org.apache.pulsar.client.impl |
connections, reconnects, producer and consumer lifecycle; noisy at INFO |
org.apache.pulsar.client.impl.auth.oauth2, com.nimbusds |
OAuth2 token fetching; the place to look when authentication fails |
Keep Pulsar at WARN rather than ERROR: connection and authentication problems are logged below ERROR.
One Pulsar client per connection
KlokPulsarClientManager keeps one PulsarClient per connection and hands it out to every KlokBrokerClient whose
configuration has that connection (acquireClient/releaseClient). The connection is the service URL, the OAuth2
issuer, client id, secret and audience, and the trusted CA file. The route id, the instance name and the listener
threads are not part of it: each KlokBrokerClient keeps its own and uses them for the metric prefix, the
klok-route-id and klok-instance metadata of its consumers and producers (see What the broker
shows) and its own listener thread
pool. A Quarkus service with twenty routes, whose extension gives every route a configuration of its own that differs
only in the route id, therefore holds one connection and one token, not twenty. Up to 0.3.8 the cache was keyed on the
whole configuration, route id included, and such a service opened one Pulsar client per route.
The reference count decides the lifetime: the Pulsar client is closed when the last KlokBrokerClient that uses it is
closed. No JVM shutdown hook is registered, so a Pulsar client whose KlokBrokerClients are never closed stays open
until the process ends; close every client when the application stops. shutdownAll() closes every Pulsar client at
once and is meant for tests.
Bytes client
KlokBytesBrokerClient is the client for services that bring their own payload encoding: Protobuf, FlatBuffers, a
pre-encoded Avro record, or a relay of payloads it does not interpret. Payloads are byte[] and go on the wire as
given, with Pulsar's Schema.BYTES, so the client does no serialization or deserialization. Use it when the Avro
serialization of the typed client is unnecessary or slower than the service's own codec; otherwise use
KlokBrokerClient<T>, which also registers the datamodel schema on the topic.
It is the same client underneath, KlokBrokerClientSync<byte[], byte[]> with the bytes schema, so it has the same
configuration, klok-* properties and CloudEvents attributes, KlokSubscriptionOptions (type, initial position,
concurrency, negative acknowledgement delay), acknowledgement contract, metrics and request/reply topics as the typed
clients, and a bytes service and a typed service answer each other.
try (KlokBytesBrokerClient client = new KlokBytesBrokerClient(KlokBrokerClientConfig.buildFromEnv(), openTelemetry)) {
client.subscribe(topic, KlokSubscriptionOptions.builder("fast-ingress")
.subscriptionType(SubscriptionType.Shared).concurrency(8).build(),
message -> handle(OrderProto.parseFrom(message.getPayload())));
client.sendMessage(topic, order.toByteArray(),
Map.of(KlokMessageProperties.CORR_GLOBAL, globalId, KlokMessageProperties.CORR_PLATFORM, platformId,
KlokMessageProperties.BODY_TYPE, "application/x-protobuf"), order.getId());
// request/reply: ..._Request is answered on ..._Response
client.handleRequests("persistent://acme/common/ReqRes_PriceQuery_Price_Request", "price-service",
request -> price(request.getPayload()));
KlokBrokerMessage<byte[]> reply = client.sendRequestReply(
"persistent://acme/common/ReqRes_PriceQuery_Price_Request", query, globalId, 2_000);
}
What differs from the typed client:
- Topics are named. A
byte[] has no datamodel class to derive a topic from, so the Class-based sendMessage and
subscribe overloads throw UnsupportedOperationException; pass the full topic name.
klok-body-type is application/octet-stream unless the sender sets it in the properties (for example
application/x-protobuf), so a reader can choose its decoder.
- Canonical names only. It writes the
klok-* property names without their 0.2.x camel case duplicates, which exist
for 0.2 readers of typed topics. Every property is parsed per message on both sides, so the duplicates cost throughput a
bytes service has no use for.
- No schema on the topic. The broker does not validate the payload; the body type and the topic name are the contract
between the services.
Performance
With the broker on the same machine, one receive loop and a 301-byte payload, the bytes client published about twice as
many messages per second as the typed client and consumed about 1.5 times as many, because it spends about 5 ns per
message on the payload where Avro spends about 1.1 µs. The figures, the message size, how they were measured, the
environment, and what network latency does to them are in the user guide: Broker Throughput And
Capacity. How to run the
benchmark is under Testing. The remaining consume gap to the bytes client of 0.3.4 is tracked in
#29.