Authentication and subscriptions

Authentication

The client authenticates with OAuth2 client credentials: it fetches a token from the Keycloak realm at authUrl with authClientId/authClientSecret and audience pulsar, and the Pulsar client presents that token on the connection. A service's credentials reach the container through its Vault env object (KLOK_BROKER_AUTH_CLIENT_ID, KLOK_BROKER_AUTH_CLIENT_SECRET).

The broker checks the token of every live connection every 60 seconds and closes a connection whose token has expired. The client has Pulsar's OAuth2 plugin fetch a new token after 80 % of the token's lifetime (earlyTokenRefreshPercent), so the check never meets an expired one; up to 0.3.10 the plugin kept a token until it had expired by the client's clock, and a connection could be closed in between (see Connection health).

Authorization is enforced by the broker, from the grants the service's role holds. The role of a client is service-account-<client id> of its OAuth2 client (KlokBrokerClientConfig.brokerRole()). A missing grant shows up as a KlokTopicAccessDeniedException that says which grant to request (see Missing topics and grants below). Who creates a service's Keycloak client and which grants it gets are described once, in the framework development guide: Service Identities and Broker Access And Tenant Isolation.

The connection to the platform broker is TLS: the client trusts the Klok Root CA (or the configured CA file) and verifies that the broker's certificate names the host it connects to. See TLS in Configuration. The Python and TypeScript clients run the token request inside the native Pulsar client, which verifies the issuer (auth.ipaas.se, a Let's Encrypt certificate) with the same CA file, so their file also holds the public roots (One CA file for the broker and the issuer in Design decisions).

klok.broker.auth.enabled=false (Quarkus) or a blank authUrl given to the builder (plain client) disables authentication, which is only meant for tests and local development against an unsecured broker. build() still requires a client id and a secret, any value: the Quarkus extension passes none. An empty KLOK_BROKER_AUTH_URL does not switch it off, since an empty variable counts as unset and the default issuer is used; the Python and TypeScript clients do switch it off, as the wire contract says (#13).

Missing topics and grants

Topics on the Klok broker are never created automatically (klok5 runs with allowAutoTopicCreation=false; the rule is topics.provisioning in klok-common's wire contract). A topic exists only when it is listed in its tenant's Pulsar file in Git and that file has been applied, and its _DLQ (and the _Response of a _Request topic) is created with it. When a topic the client needs is missing, or its role holds no grant for what it tries, the client says so with one of two exceptions, both KlokBrokerClientExceptions:

Exception Code Pulsar error behind it
KlokTopicMissingException TOPIC_MISSING TopicDoesNotExistException, NotFoundException (the HTTP lookup's 404)
KlokTopicAccessDeniedException TOPIC_ACCESS_DENIED AuthorizationException, NotAllowedException

Both extend KlokTopicProvisioningException, which carries getTopic() (the full name), getRole(), getOperation() (PUBLISH or CONSUME) and getCode(), and is never retryable (isRetryable() is false): the same call fails again until a person changes Git. Their message is exactly the text klok-common's KlokTopicProvisioning renders, the same in every Klok client and tool:

TOPIC_MISSING: the topic persistent://acme_dev/finance/InvoiceV1_created does not exist, so service-account-acme-invoice-egress cannot publish on it.
Topics are never created automatically on the Klok broker. A topic exists only when it is listed in its tenant's Pulsar file in Git and that file has been applied; its _DLQ topic, and the _Response topic of a _Request topic, are created with it.
Request the topic in klok.dev: https://klok.dev/monitoring/broker/request?topic=persistent%3A%2F%2Facme_dev%2Ffinance%2FInvoiceV1_created&access=create
It is approved by a TenantAdmin of acme or a DomainAdmin of acme/finance.
By hand: add `- persistent://acme_dev/finance/InvoiceV1_created` under `topics:` in ansible-master/playbooks/group_vars/all/pulsar_tenant_acme.yml in the repository klok/environment/klok-environment-setup, in a merge request; after the merge it is applied on the broker.
More: https://docs.klok.dev/klok-framework-klok-common/common/naming-conventions/

The klok.dev base URL of the request link is KLOK_DEV_URL (see Configuration).

What the Pulsar 5.0 client does against such a broker, and therefore what the client maps:

  • A missing topic fails the producer, the consumer, a reader and a lookup alike with TopicDoesNotExistException (the partitioned metadata lookup fails before anything is created).
  • A role without a grant fails them with AuthorizationException (Client is not authorized to Produce, or to Get Partition Metadata for the lookup). The broker checks the grant before it looks for the topic, so a topic that is missing and not granted is reported as denied; the message says that the topic may need to be listed too.
  • A consume grant allows consumers, readers and lookups, not producers; a produce grant the other way round.

Where it surfaces:

Path What the caller gets
sendMessage the future completes with the exception itself
subscribe, subscribeWithOutcome, subscribeBatch the exception is thrown
verifyPublish, verifyConsume the exception is thrown
KlokBrokerClientSync.sendReply, handleRequests the reply future completes with the exception itself
KlokBrokerClientSync.sendRequestReply (request producer, reply consumer) a KlokRequestNotSentException (a KlokRequestReplyException: the request never left) whose message is the contract text and whose cause is the exception
a dead letter to a missing _DLQ the receive loop stops, see below

KlokTopicProvisioningException.find(throwable) finds it in any cause chain, for example in the ExecutionException of a send or in a KlokRequestReplyException. Every other failure keeps its type (KlokSendMessageException, KlokBrokerClientException, KlokRequestReplyException) with the Pulsar error as its cause.

Checking topics at startup

verifyPublish(topic) and verifyConsume(topic, subscription) check a topic before the first message needs it, so a service can stop at startup with the fix instead of failing its first message:

client.verifyPublish("persistent://acme/finance/InvoiceV1_created");
client.verifyPublish("persistent://acme/finance/InvoiceV1_created_DLQ");   // the dead letter producer, created eagerly
client.verifyConsume("persistent://acme/finance/OrderV1", "ACM001E1_Invoice");
  • verifyPublish creates the producer that the client's sends use, or finds it in the cache, so it costs nothing afterwards and a _DLQ producer exists before the first dead letter.
  • verifyConsume opens a reader (a non-durable subscription <subscription>-verify-<8 hex>, from the latest message) and closes it again. The broker authorizes a reader as a consumer, so it proves that the topic exists and that the role may consume it, and it leaves nothing on the topic: the durable subscription is still created by subscribe. Why it is not a lookup or a durable subscription is in Design decisions.
  • Both throw the two exceptions above, and a plain KlokBrokerClientException when the broker cannot be reached.

When a topic disappears under a running client

  • A producer whose topic is deleted is closed by Pulsar for good. The next send drops it from the cache and creates it once more, which either works (the topic is back) or fails with KlokTopicMissingException; it is never retried in a loop. The same holds for the dead letter producer and, on the next request or reply, for KlokBrokerClientSync.
  • A consumer whose topic is deleted is closed and failed for good by Pulsar (its receive then throws NotConnectedException or AlreadyClosedException). The receive loop looks the topic up (a lookup that never creates it, up to four times half a second apart, since the broker disconnects the clients before the topic is gone from its metadata), logs the contract message, or the Pulsar error when the topic is still there, at ERROR and stops. runningReceiveLoops drops to zero and receiveLoopFailure(topic, subscription) returns why; subscriptionHealth() reports it to a health check. A restart subscribes again.
  • A dead letter topic that is missing or refused stops the loop too: the message in hand is negatively acknowledged once and stays on the subscription, and the loop ends with the _DLQ's contract message, instead of receiving the same message again forever. Once the _DLQ exists, a restarted subscription dead letters it.

Subscriptions

client.subscribe(topic, KlokSubscriptionOptions.builder("KLK002E1_OdlPersist")
        .subscriptionType(SubscriptionType.Exclusive)          // default
        .initialPosition(SubscriptionInitialPosition.Latest)
        .negativeAckRedeliveryDelayMs(60_000)
        .ackTimeoutMs(0)
        .receiverQueueSize(1000)
        .build(), message -> { ... });
  • The subscription name is the route id by convention, so the broker's subscription list reads like the list of consuming routes. A second instance of the same service with an Exclusive subscription is refused, which is the intended behaviour for routes that must process in order; Shared or Key_Shared are opted into per route (<RouteId>.subscription.type in the extension).
  • A handler that returns normally acknowledges the message. An exception negatively acknowledges it and the broker redelivers after negativeAckRedeliveryDelayMs. The Quarkus extension does its own retries with backoff and republishes to <topic>_DLQ before that point, so the broker level redelivery is the safety net, not the retry.
  • A handler that has to decide the acknowledgement itself, because a failure was neither delivered nor quarantined, uses subscribeWithOutcome with a KlokMessageHandler: it returns KlokHandlerOutcome.ACKNOWLEDGE or NEGATIVE_ACKNOWLEDGE. A requested negative acknowledgement is logged as a warning without a stack trace (the handler already logged why), counted as consumer.nack.requested, and the message is redelivered; an exception is still an error. Both forms go through the same Consumer overload, which stays the single method a test double overrides.
client.subscribeWithOutcome(topic, options, message -> {
    Disposition d = process(message);            // delivered, quarantined or unresolved
    return d == Disposition.UNRESOLVED ? KlokHandlerOutcome.NEGATIVE_ACKNOWLEDGE : KlokHandlerOutcome.ACKNOWLEDGE;
});
  • deadLetterPolicy enables Pulsar's native dead letter topic; it requires a Shared or Key_Shared subscription, and the client sets it only when the options carry one. The Quarkus extension has no route key for it: its routes use the framework managed _DLQ republish, and a route that wants the native policy overrides subscriptionOptions(String). Whether the extension should offer it as configuration is klok-quarkus-extension#44.
  • A message whose payload cannot be decoded (another schema, a truncated or foreign payload) never reaches the handler. The client logs it at ERROR with topic, message id and schema version, republishes its bytes unchanged to <topic>_DLQ with its properties plus klok-error-code=DECODE_ERROR, klok-error-message, klok-retry-count=0, klok-original-topic, klok-original-message-id and klok-failed-route-id, and acknowledges it, as the Python client does: no retry can help it. With deadLetterUndecodable(false) in the options, or when the dead letter publish fails, it is negatively acknowledged instead; when the _DLQ topic is missing or refused, the receive loop also stops (see Missing topics and grants). deadLetterTopic(topic -> ...) in the options names another dead letter topic for a consumed topic. A service that reads another domain's or tenant's topic may not publish beside it (write narrow, consume wide), so from klok-quarkus-extension 3.18.0 the extension passes its own rule there, the same name in the service's own tenant and domain (klok-quarkus-extension#76); without it the dead letter topic stays <topic>_DLQ. The Quarkus extension does not set deadLetterUndecodable yet, so its routes dead letter undecodable messages even with <RouteId>.dlq.enabled=false; mapping that key onto the option is klok-quarkus-extension#25. The dead letter is sent with Schema.BYTES, which keeps the bytes exactly as they arrived and which the broker accepts on a topic with a schema unless the namespace enforces schema validation. Up to 0.3.2 such a message was neither acknowledged nor negatively acknowledged and stayed on the subscription until the consumer reconnected, then failed again (#7). A reply that cannot be decoded fails its request at once with a KlokRequestReplyException and is acknowledged like every reply; a reply no request of the client waits for is never decoded at all (see Request/reply).

Concurrency

By default a subscription handles one message at a time: the client runs one receive loop on the consumer, the loop calls the handler and acknowledges before it receives the next message. That is the strictly ordered mode the ODL materializers rely on. A subscription whose messages are independent, such as an AI worker or an ODL search service, sets a concurrency and the client runs that many receive loops on the same consumer:

client.subscribe("persistent://klok/common/KlokAiTaskRequestV1_ai.transcribe-pdf",
        KlokSubscriptionOptions.builder("KLK003E4_TranscribePdfWorker")
                .concurrency(4)
                .build(),
        message -> transcribe(message));
  • Each loop receives, handles and acknowledges its own message, so the acknowledgement rules above are unchanged; only the number of messages in flight per client instance changes.
  • A concurrency above one switches the subscription type to Shared unless a type was set explicitly, so that a second instance of the service can join the same subscription. Key_Shared set explicitly keeps the order per message key while handling different keys in parallel. Exclusive set explicitly with a concurrency above one is allowed: one instance, several loops, no ordering.
  • Any concurrency above one gives up the order of the subscription; the client cannot restore it.
  • The loops run on the client's listener thread pool, one thread per loop for the lifetime of the subscription. The pool is sized by listenerThreads in the configuration (KLOK_BROKER_LISTENER_THREADS, default 20) and grows on subscribe when the subscriptions of the client need more, with a log line naming the subscription that made it grow. The configured value is a floor, not a limit.

In the Quarkus extension the same option is the route key <RouteId>.subscription.concurrency (with the usual route, solution and klok.route-defaults fallback), so it is set per route in application.properties or from the service's Vault env secret without code changes.

Batches

A subscription whose handler is cheaper per message in bulk, such as an OpenSearch writer that can send one _bulk request instead of one request per message, subscribes with subscribeBatch. The receive loop waits for a first message, then takes what arrives until the batch is full or the wait has passed, and hands the whole batch to the handler, which answers with one outcome per message:

client.subscribeBatch("persistent://klok/common/KlokOdlDeleteV1",
        KlokSubscriptionOptions.builder("KLK002E3_OdlDeleteFromOpensearch").build(),
        new KlokBatchPolicy(500, 1000),           // up to 500 messages, at most 1 s after the first one
        batch -> deleteAll(batch));               // List<KlokHandlerOutcome>, one per message, in order
  • Nothing is acknowledged before the handler returned. Each message is then acknowledged or negatively acknowledged by its own outcome, so a crash in the middle of a batch redelivers all of it, and one failed item is redelivered alone. A handler that throws, or answers with the wrong number of outcomes, negatively acknowledges the whole batch.
  • A backlog is drained in full batches. Messages already in the consumer's receiver queue are taken at once, so the wait only applies when the topic is quiet; then a batch of one leaves after maxWaitMs.
  • A message whose payload cannot be decoded never reaches the handler and is dead lettered or negatively acknowledged exactly as in a single message subscription.
  • concurrency is the number of batches in flight per client instance; with Key_Shared every batch holds keys of its own consumer.
  • The batch has no single correlation id, so the client puts none into the MDC; a handler that logs per message sets it itself.

The Java client has batch subscriptions; the Python and TypeScript clients handle one message at a time.

What the broker shows about a consumer and a producer

Pulsar keeps the properties a client gives a consumer or a producer when it creates it, and shows them as metadata in the topic stats. Every Klok client (Java from 0.3.6, the TypeScript and Python clients from the same merge) attaches the metadata the wire contract of klok-common states under messaging.clientMetadata, with the names of KlokClientMetadata:

Key On Value
klok-route-id every consumer and producer the route that owns it
klok-instance every consumer and producer the running instance (klok.instance, KLOK_INSTANCE)
klok-subscription-concurrency every consumer the receive loops the client runs on the consumer, a decimal integer

The stats of a topic list them per consumer of each subscription and per publisher:

curl -s -H "Authorization: Bearer $TOKEN" \
  "https://<broker admin>/admin/v2/persistent/klok/common/KlokAiTaskRequestV1_ai.chat/stats" \
  | jq '{subscriptions: (.subscriptions | map_values([.consumers[].metadata])), publishers: [.publishers[].metadata]}'
{
  "subscriptions": {
    "KLK003E1_ChatWorker": [
      {"klok-route-id": "KLK003E1_ChatWorker", "klok-instance": "<instance of the pod>", "klok-subscription-concurrency": "80"}
    ]
  },
  "publishers": [
    {"klok-route-id": "<publishing route>", "klok-instance": "<its instance>"}
  ]
}

How to read it:

  • One pod is one consumer, however high its concurrency. A client opens one consumer per topic and subscription and runs its receive loops on it, so the broker counts consumers: 1 for a pod with concurrency 80. The work in flight on a subscription is the sum of klok-subscription-concurrency over its consumers, not the number of consumers.
  • unackedMessages is not work in progress. It includes what the consumer has fetched ahead into its receiver queue (receiverQueueSize, 1000 by default in Pulsar), not only the messages the loops are handling.
  • A reader is identified by its subscription name, never by the topic. A topic is always <Model>[_<purpose>]: the purpose is the flow the publisher chose, which the reader matches. Who reads it shows up as a subscription named after the reading route (DGR012E1_… for a route of another tenant, whose short name is in the route id) and as that route's klok-route-id on the consumer.
  • A key without a value is left out, not sent empty (the Pulsar builders refuse a blank value). A client from before this change shows no metadata at all.

What each client puts in:

  • Java. klok-route-id is the configuration's routeId and klok-instance its klokInstanceName. The Quarkus extension sets routeId to the owner of each client it creates: the route id for a route's own client, and the route id with a suffix for a route's second client (<RouteId>-out for a processing route's publisher, <RouteId>-result for an offramp's result publisher, <RouteId>-events for the CloudEvents publisher), so a reader of the stats takes the route id as the part before the first -. A subscription's consumer states KlokSubscriptionOptions.concurrency(). Producers of payloads, of requests and replies (KlokBrokerClientSync) and of dead letters carry the route and the instance; the reply consumer of KlokBrokerClientSync runs one loop and states 1. A second subscribe on the same topic and subscription in one client reuses the consumer, whose metadata keeps the concurrency of the first.
  • TypeScript and Python. The route of a subscription is its routeId / route_id option, else the client's KLOK_ROUTE_ID, else the subscription name; producers carry the client's KLOK_ROUTE_ID. Both clients read replies with a non-durable reader, and a Pulsar reader takes no properties, so their reply subscriptions carry no metadata.

Receive loops survive reconnects

A receive loop runs until the client is closed, its thread is interrupted, or Pulsar has given up on its consumer, and for no other reason. While Pulsar reconnects a consumer (a broker restart, a topic unload by the load balancer, a network interruption, a failed token refresh) receive returns nothing and the loop simply receives again; the consumer's connection state is never consulted. A receive that fails otherwise is retried after a pause that doubles from 100 ms up to 5 s. A consumer that Pulsar closed or failed for good (its topic deleted, which on a broker without automatic topic creation it never comes back from) ends the loop at ERROR with the reason, which receiveLoopFailure returns (see Missing topics and grants); up to 0.3.9 such a loop logged the same error every five seconds forever. A loop that ends while the client is open logs at WARN (interrupted) or ERROR (anything else). An Error is no reason either: see An Error in a handler below.

Up to 0.3.2 the loop also stopped as soon as the consumer reported itself disconnected, which after any broker restart left the subscription attached but without a thread receiving from it (#6).

client.runningReceiveLoops(topic, subscriptionName) returns the number of loops running for a subscription (its concurrency while it consumes). A loop that ended while its client is open counts in client.subscriptionHealth(), and the watchdog logs it on every check (KLOK_BROKER_CONNECTION state=RECEIVE_LOOP_STOPPED), since a consumer with no loop left stays connected and holds on to its subscription and its queued messages while nothing reads them.

A loop that keeps running does not mean its consumer is connected. The connection watchdog reports a consumer that stays disconnected (KLOK_BROKER_CONNECTION state=DISCONNECTED kind=consumer) and lists it in connectionHealth(); see Connection health.

An Error in a handler

A handler that throws a Java Error gets the same as one that throws an exception: its message is negatively acknowledged, and the loop receives the next one. The loop does that on a new thread, so that the next message does not meet what the handler left on the old one. What differs between the errors is what they say about the process, and KlokHandlerErrors holds that rule:

What the handler threw What it means The message The receive loop Subscription health
StackOverflowError the failure of that message: deep recursion on this input, which the same input repeats. The stack is unwound by the time the client catches it negatively acknowledged goes on healthy
OutOfMemoryError, InternalError, UnknownError (every other VirtualMachineError) the process cannot be trusted any more negatively acknowledged goes on unhealthy until the service is restarted
anything else, such as NoClassDefFoundError or AssertionError the failure of that message negatively acknowledged goes on healthy

client.subscriptionHealth() is that last column; see Connection health.

All of this holds for a batch, whose messages are all negatively acknowledged, and for the handler of handleRequests. A payload that overflows the stack of the decoder never reaches the handler and is dead lettered with DECODE_ERROR, like any other payload that cannot be read. A decoder that runs out of memory says nothing about the payload, so that message is only negatively acknowledged. In a requester's reply loop an Error fails the one request whose reply it was, and the loop goes on.

Negatively acknowledging means that the broker sends the message again after the subscription's negative acknowledgement delay, so a message that overflows the stack comes back every time, as a message whose handler throws an exception does, until the subscription's dead letter policy takes it. The Quarkus extension does better: it turns the error into a failure of the route step, which is dead lettered at once.

Why it is built this way is in the design decisions.

Request/reply

KlokBrokerClientSync<T, U> is created with the request and reply topics (ReqRes_<Req>_<Res>_Request and _Response, resolved to full names). sendRequestReply(request, correlationId, timeoutMillis, properties) publishes the request with klok-reqres-id, klok-reply-topic and klok-reply-subscription, then waits for the reply that carries the same id on the reply topic. On the server side sendReply(request, replyPayload, properties) copies the id and the chain context, and handleRequests does it for every request it answers. KlokRequestReplyException signals a timeout or a broker failure; which Klok error code it becomes is the caller's choice (the Quarkus extension's KlokOdl reports every such failure as UPSTREAM_UNAVAILABLE).

Its subclass KlokRequestNotSentException says that the request provably never left: the client has no default topic, nobody could read the reply, the request producer could not be created, or the send failed before the message went over the connection. Nothing can have run such a request, so it is the one failure a caller may answer by sending the request again. A request that was sent and got no reply in time may have run, and so may one whose send timed out or whose producer closed under it, since the broker can have stored it all the same: those stay a plain KlokRequestReplyException. Why: A request that never left says so in Design decisions.

A request whose send times out drops the request producer, and the next request creates a new one (KLOK_BROKER_CONNECTION state=SEND_TIMEOUT); the request producer and the reply consumer are also created again when they stay disconnected (see Connection health). A request or reply topic that is not provisioned is a KlokRequestNotSentException with the contract message and a KlokTopicMissingException or KlokTopicAccessDeniedException as its cause; a missing reply topic fails the request before anything is sent. KlokBytesBrokerClient is the same client with Schema.BYTES, so all of this holds for it too.

Every requester of a pair shares the response topic, so the replies are addressed:

  • The reply subscription is non-durable. The client reads each reply topic with one consumer of its own, subscription reply-subscriber-<clientId>-<uuid> (getReplySubscriptionName(), the same name on every reply topic of the client), SubscriptionMode.NonDurable, from Latest, created before the first request on the topic is sent. The broker keeps a non-durable subscription only while its consumer is connected: it is gone from the topic stats after close() and as soon as a crashed or killed process loses its connection, so nothing is left behind that collects replies (#10). Up to 0.3.6 the subscription was durable and never removed, and every restart of a requester left one more subscription that kept every reply of the pair as backlog.
  • The request names it. Every request carries klok-reply-subscription (KlokMessageProperties.REPLY_SUBSCRIPTION) with that exact name; a value the caller passes in properties is replaced.
  • The replier keys the reply with it. sendReply gives the reply the message key (partition key) of the request's klok-reply-subscription and copies the property onto the reply. A request without the property, from an older requester, gets a reply without a key, as before. Reply producers batch by key (BatcherBuilder.KEY_BASED), so one batch, which the broker stores as one entry with one key, only ever holds replies to one subscription.
  • The broker delivers the reply to that subscription only. The Pulsar entry filter of klok-pulsar-entry-filter runs on the brokers and lets an entry whose key starts with reply-subscriber- through only to the subscription of that name, or to a reader subscription named <key>-reader-<random>; every other subscription, and every entry without such a key, is untouched. Without the filter every live requester of the pair receives every reply, as before.
  • Python and TypeScript requesters are addressed by their reader's prefix. Their libraries read replies with a reader, whose subscription is <prefix>-reader-<random>; the clients use reply-subscriber-<clientId>-<uuid> as the prefix and send it in klok-reply-subscription, so a Java replier's reply reaches them alone as well.
  • The requester still pairs by id. The reply loop reads klok-reqres-id from the properties first and decodes a reply only when one of its requests waits for it; any other reply (another requester's on a broker without the filter, or one that came after its request timed out) is acknowledged without decoding it.
  • A request is pending as long as it waits. A pending request is kept for its own timeoutMillis, and a reply that comes later belongs to no pending request (the wire contract's requestReply.pendingReplyLifetime). Up to 0.3.13 every pending request expired 30 seconds after it was sent, so a reply that took longer was lost to a request that waited longer, and the requester answered its own caller with a timeout (#9).

Old and new clients mix in both directions: a reply to a request without klok-reply-subscription has no address and reaches every requester, which passes over what is not its own, and an old requester ignores the property on a reply.

Metrics and MDC

KlokPulsarClientUtil.initLoggingOpenTelemetry() registers a metric exporter (KlokSingleLineSummaryMetricExporter) that logs a one line summary of producer and consumer counters per route id.

The client puts the correlation ids of a received message into the MDC so handler log lines are correlated: klok.corr-global and klok.corr-global-source (from getCorrGlobalWithSource()), klok.corr-platform (from getCorrPlatform(), which falls back to klok-correlation-id for a message of a service built before the three ids), and camel.breadcrumbId as the global id, so a Camel route the handler runs continues it. The earlier key klok.correlation-id is gone. The service id (klok.corr-service) is not the client's to set: the route that handles the message creates it. The field names are on the klok-common page Log Fields And Correlation. It never leaves logging context behind on a thread it does not own; every place that touches the MDC runs inside a KlokMDC scope, which puts the thread's previous map back when it closes:

  • Subscriptions. dispatch restores the listener thread's MDC after each message, including every key the handler added (the extension's klok.invocation-id, klok.task-id, klok.route-id, ...). A message without a task id is therefore never logged with the task id of the previous message on that thread.
  • Sends. sendMessage captures the caller's MDC and, in the sendAsync() callback, replaces the MDC of the thread that completes the send (normally a Pulsar IO thread) with it: the publish error and every continuation the caller chains on the returned future log with the caller's context, and the IO thread gets its own MDC back afterwards. When the send is already complete and the callback runs inline, the caller's MDC is unchanged.
  • Replies. KlokBrokerClientSync sets the breadcrumb of a reply only while the requester's future is completed.

KlokMDC.with(map) and KlokMDC.preserve() are public for code with the same problem. KlokMDCHelper.addFromCopy, which only added keys and never removed them, is deprecated for removal.