Connection health

A service whose producer or consumer has lost its broker connection is broken, whatever its pod says. The Java client watches every producer and consumer it holds, says loudly in the console log when one stays disconnected, creates producers and reply consumers again, and tells a health check what it sees. This page is for the developer who builds on the client and for the operator who gets the alert.

Why it exists

On 2026-10-09 the broker rejected the token of klok-documentation-egress at 01:10:07 (ClientCnx: Failed to authenticate the client) and closed its connection. Pulsar reconnected the service's reply consumer within a second, but its request producer never registered with the broker again. The client kept sending on it, and every request waited until the producer's 30 second send timeout. That went on for more than four hours, until a person restarted the pod. The pod was Running and Ready all along, and nothing reported anything (#34).

Two things in the client let that happen, and both are fixed:

  • The token was used until it had expired. Pulsar's OAuth2 plugin kept a token until it had expired by the client's clock, which is later than the token's exp by the round trip to Keycloak. The broker checks the token of every live connection every 60 seconds with no leeway, so a check in between rejects a token the client still uses. The client now has the plugin fetch a new token after 80 % of the token's lifetime (earlyTokenRefreshPercent).
  • Nothing looked at the connection of a producer. The client replaced a producer only when Pulsar had closed it. A producer that stayed disconnected was kept and sent on for ever. Now the watchdog below finds it.

What the watchdog does

One watchdog per JVM checks every producer and consumer of every open KlokBrokerClient every 10 seconds:

A handle that is Is
disconnected for less than 30 seconds quiet: Pulsar is reconnecting it, which usually takes under a second
disconnected for 30 seconds or more logged at ERROR on every check, state=DISCONNECTED
a producer, still disconnected after 60 seconds closed and created again (state=RECOVERING); a failed attempt is logged (state=RECOVERY_FAILED) and tried again every 30 seconds
a requester's reply consumer, still disconnected after 60 seconds closed and subscribed again, the same way; it is non-durable, so a new one loses nothing
a consumer of a subscription logged, never replaced: Pulsar keeps reconnecting it, and a second consumer on an exclusive subscription would be refused while the first is attached
connected again after an outage that was logged logged at WARN, state=RESTORED

The checks also report two things a connection does not show, since a consumer without a thread that reads from it is still connected. Neither goes away by itself, so both are logged at ERROR on every check until the service is restarted:

What is wrong Is logged as
a receive loop of a subscription ended while its client is open (its topic was deleted, its _DLQ is missing, its thread was interrupted) state=RECEIVE_LOOP_STOPPED kind=consumer, with the reason
the JVM had a fatal error, such as an OutOfMemoryError in a handler (see An Error in a handler on Authentication and subscriptions) state=FATAL_ERROR kind=jvm, with the error and where it happened

Two more rules work without waiting for the next check:

  • A send that times out drops its producer (state=SEND_TIMEOUT), and the next send creates a new one. This holds for plain sends, the requests of request/reply, replies and dead letters.
  • A producer disconnected for 60 seconds or more is dropped before a send, and the send goes to a new one, instead of into a queue that only times out.

Producers are created again without holding the client's producer lock, and creating one may take at most 60 seconds; one that arrives later is closed. A creation that hangs neither blocks the client's other sends nor the watchdog.

The client does not rebuild the shared Pulsar client. Every route of the service shares it, with its consumers, their receive loops and their unacknowledged messages, and swapping it under them is riskier than starting the service again. A service whose broker connection does not come back is restarted by its health check instead (see Health checks below).

The log contract

Every line about a broker connection contains the token KLOK_BROKER_CONNECTION and key=value fields, on the logger dev.klok.brokerclient.connection:

KLOK_BROKER_CONNECTION state=DISCONNECTED kind=producer topic=persistent://klok/common/ReqRes_KlokOdlGetV1_KlokOdlGetResponseV1_Request subscription=- owner=KlokOdl instance=klok-documentation-egress for=45s attempt=0 - not connected to the broker; the client creates it again after 60s
Field Value
state DISCONNECTED, RECOVERING, RECOVERY_FAILED, SEND_TIMEOUT, RECEIVE_LOOP_STOPPED, FATAL_ERROR (ERROR, broken) or RESTORED (WARN, healthy again)
kind producer, dead-letter-producer, reply-producer, consumer, reply-consumer; jvm for FATAL_ERROR, which belongs to no handle
topic, subscription the handle's topic, and its subscription (- for a producer and for kind=jvm)
owner, instance the route id and the instance name of the client that holds it (- for kind=jvm)
for how long it has been disconnected, stopped or failed, in whole seconds
attempt how many recovery attempts this outage has had

The text after - is for people and may change; the fields before it are the contract. Every state but RESTORED means broken, and a broken handle is logged at least every 10 seconds for as long as it lasts, so "no broken line in the last five minutes" means healthy. The Pulsar client's own ClientCnx line Failed to authenticate the client (ERROR) is the other line worth an alert: it means the broker rejected the service's token.

The lines go to the console, never over the broker. The Klok log events (KLK001) travel over the broker and are lost exactly when the connection is broken, so an alert on broker connections reads the Kubernetes console logs, which Fluent Bit ships to OpenSearch (klok-logs-<namespace>-console-*).

Settings

The defaults suit every Klok service; change them only to test. Each is read once per JVM, from a system property, else an environment variable.

System property Environment variable Default
klok.broker.health.enabled KLOK_BROKER_HEALTH_ENABLED true
klok.broker.health.check-interval-ms KLOK_BROKER_HEALTH_CHECK_INTERVAL_MS 10000
klok.broker.health.grace-ms KLOK_BROKER_HEALTH_GRACE_MS 30000
klok.broker.health.recover-after-ms KLOK_BROKER_HEALTH_RECOVER_AFTER_MS 60000
klok.broker.health.recover-retry-ms KLOK_BROKER_HEALTH_RECOVER_RETRY_MS 30000
klok.broker.health.create-timeout-ms KLOK_BROKER_HEALTH_CREATE_TIMEOUT_MS 60000

enabled=false stops the checks only; a send that times out still drops its producer. The unit tests of this repository run with the watchdog off and drive one of their own.

Health checks

client.connectionHealth() returns KlokConnectionHealth for one client, and KlokConnectionHealth.ofAllClients() for every open client in the JVM. Each Handle names its kind, topic, subscription, owner and instance, whether it is connected, how long it has been disconnected and how many recovery attempts the outage has had. broken() lists the handles disconnected for at least the grace period, healthy() says there are none, and longestOutageMillis() is the longest outage.

client.subscriptionHealth() returns KlokSubscriptionHealth for one client, and KlokSubscriptionHealth.ofAllClients() for every open client in the JVM. Each Subscription names its topic, subscription, owner and instance, how many receive loops run, how many ended and when, and why. stopped() lists the subscriptions with a loop that ended, fatalError() says what fatal error the JVM had, and healthy() says there is neither. A client that was closed has no subscriptions left, so closing one is not a stopped loop.

A plain Java service calls both from its own health endpoint, and its liveness check goes DOWN when KlokSubscriptionHealth is unhealthy, since nothing but a restart cures it. A service without such a check keeps running on what is left, loudly. The Quarkus extension does this with no code; see Health checks there.

KlokBrokerClient.isConnected() is unchanged: it says that the client is open, not that its producers and consumers are connected.

When a service logs a broken connection

The pod that logged the line is the service; the line names the topic and the handle. Take these steps:

  1. Read the line. RESTORED after a DISCONNECTED was a broker restart or a network blip that healed by itself. A RECOVERY_FAILED that repeats, or DISCONNECTED lines for a consumer that do not stop, mean the service cannot reach the broker. RECEIVE_LOOP_STOPPED and FATAL_ERROR do not come from the connection, and only a restart ends them: go to the last step. FATAL_ERROR names the error and the topic or route where it was seen. When the service runs out of memory again right after the restart, on the same topic, one message is doing it: the message comes back to the new process, and a person has to decide about it.
  2. Check the broker side: the topic's publishers and subscriptions in topics stats show whether the producer or consumer is registered. A Caller Can Lose Its Request Producer And Blame The ODL on the gotchas page of the Klok Framework Development Guide shows how.
  3. A Failed to authenticate the client line means the broker rejected the token: check the service's Keycloak client and its secret in Vault.
  4. If it does not recover by itself, restart the service — with a person's yes. A restart builds a new Pulsar client and a new token.

The Python and TypeScript clients have no watchdog yet (#35).