Skip to content

binding-kafka: refresh the broker table before answering a raw API stream addressed to an unknown broker id #3213

Closed

Description

@jfallows

Problem

A raw API request stream carries the id of the broker to connect to as its affinity, resolved against the route's broker table when the network stream opens. A non-zero id that the table does not know resets the stream with no fallback.

A caller is not expected to ask for a broker affinity it has not previously observed. But the cluster can scale in, so an id observed earlier can leave the table. The stream is then reset, and nothing refreshes the table: the caller's next request, addressed after it has re-discovered the broker (for example by asking again which broker to use), can still be answered from the same stale table.

Decision

The caller owns recovery: it re-issues its request, re-discovers the broker, and addresses the new id. The binding's job is to make sure the table that re-issued request meets is not stale:

  • A stream addressed to a non-zero broker id that the table does not know triggers an immediate Metadata refresh, as the fetch and produce clients do when a broker leaves or changes (metaFlush).
  • The stream is answered with the existing error (reset) only after that refresh has completed or failed. There is no retry inside the binding, even if the refreshed table now contains the id: the answer to that attempt is the error.
  • A failed refresh (cluster unreachable) still ends the stream with the error once that attempt ends, so the caller is never left waiting.

Expected

  • The behaviour above, for a non-zero id unknown to the table.
  • A stream with no broker affinity, and a stream whose id is known, behave as today.

Design first

Post a short design (or revise the one already posted): how the binding triggers the refresh in KafkaClientApiFactory and mirrors what KafkaClientFetchFactory and KafkaClientProduceFactory do, how it observes that the refresh has completed or failed so the reset is sent after it, what happens to several pending streams that all hit the same unknown id, and the interaction with clientsByAffinity. The pattern to mirror must be an existing implementation in the same module; if observing completion of the refresh needs a new mechanism, say so and ask.

Test plan (test-first)

Paired scripts under specs/binding-kafka.spec, with the spec ITs and the runtime ITs in binding-kafka: a stream addressed to an id that left the table (a second Metadata exchange happens before the reset, and the reset follows it); the same where the refresh fails; and the unchanged cases. The first commit holds the failing scripts.

Notes

Follows the change that addresses a raw API request stream to a broker by its affinity, whose description records that an unknown non-zero id resets the stream.

Activity

  1. jfallows commented on Nov 13, 2026

    @jfallows
    ContributorAuthor

    Design: recover a raw API stream addressed to a broker id the route no longer knows

    Paths are under runtime/binding-kafka/src/main/java/io/aklivity/zilla/runtime/binding/kafka/internal/stream/ (all KafkaClient*Factory, KafkaCache*Factory, KafkaMergedFactory, KafkaClientRoute, KafkaError). Line numbers are for develop at 6ee5654.

    1. How the binding recovers today

    Refresh the broker table: KafkaClientRoute.metaFlush. KafkaClientRoute keeps the route's meta streams in metaFlushes; metaFlush.accept(traceId) calls KafkaClientMetaFactory.KafkaMetaClient.doEncodeRequestIfNecessary on each. That sends a Metadata request now, unless one is already in flight (nextRequestId == nextResponseId). Without a flush the meta client refreshes only on its maxAgeMillis timer (onDecodeMetaResponse, signalAt(... SIGNAL_NEXT_REQUEST)). A Metadata response replaces the table (onDecodeBrokers: servers.clear() then putAll), rewrites topicPartitions, and sends a meta data frame to the meta stream's caller if the partitions changed.

    Who triggers it (fetch and produce clients). clientRoute.metaFlush.accept(traceId) is called:

    • when the network stream ends, aborts or is reset: KafkaClientFetchFactory.onNetworkEnd/onNetworkAbort/onNetworkReset (2389, 2414, 2432) and KafkaClientProduceFactory (1522, 1543, 1561);
    • when a response carries a retriable error code, KafkaError.of(errorCode).isRetriable(): KafkaClientFetchFactory.onDecodeFetchPartition (3028) and KafkaClientProduceFactory.onDecodeProducePartition (2405).

    The caller's stream is then reset with the error: ERROR_NOT_LEADER_FOR_PARTITION (6) is also raised locally when client.topicPartitions.get(partitionId) != leaderId (KafkaClientFetchFactory 1851 and 3238). The client factories themselves do not retry.

    Who retries (above the clients).

    • KafkaMergedFactory.onFetchPartitionError and onProducePartitionLeaderError (also reached from onFetchReplyEnd/Abort): on NOT_LEADER they re-begin the partition stream (doFetchInitialBegin / doProduceInitialBegin) with the leader from the refreshed meta.
    • KafkaCacheServerFetchFactory (1244-1271) and KafkaCacheServerProduceFactory (818): on NOT_LEADER they set leaderId = LEADER_UNKNOWN and reset the members, who re-resolve. For other errors they reconnect with backoff 50 << reconnectAttempt, capped at reconnectDelay, for as long as members is non-empty. There is no attempt count. The waiting callers end the stream. KafkaCacheBootstrapFactory.onPartitionLeaderError matches the merged factory.

    Raw API client today (KafkaClientApiFactory). It never calls metaFlush.

    • newStream (598) rejects a non-zero affinity that servers does not contain, before any client exists.
    • onNetClosed (2326) resets only the in-flight stream (cleanupAppActive), then doNetSignalReconnect (2300) retries with the same backoff formula while pending is non-empty. Each retry re-resolves the id in doNetBegin (1819).
    • If doNetBegin finds the id missing, it resets every pending stream with EMPTY_OCTETS. No refresh happens first.
    • reconnectAttempt is never reset to 0 in this factory (the cache server fetch resets it on window).
    • onDecodeResponseErrorCode handles only binding-level codes (UNSUPPORTED_VERSION). Response bodies are opaque and are never inspected for isRetriable().

    2. Can an unknown id be raised into that same path?

    Yes, with no new mechanism, but not as a fake error code on the wire. In the API client there is no retriable-code path to feed, and decoding bodies would be new. What fetch and produce share is the action behind both signals: metaFlush then a retry that re-resolves the id. Both pieces exist in this module and in this factory (doNetSignalReconnect). So "unknown id at connect" is handled as "the broker left": it fires clientRoute.metaFlush and retries through the existing backoff, which re-resolves at doNetBegin.

    Pattern to mirror: KafkaClientFetchFactory and KafkaClientProduceFactory, which call metaFlush on network close and on a retriable error. Retry stays with KafkaApiClient, using its existing doNetSignalReconnect, as KafkaCacheServerFetchFactory does with its backoff.

    3. Proposed behaviour

    1. Which ids recover. newStream admits affinity 0, an id in servers, or an id with an entry in clientsByAffinity. Such an entry exists only if the id was in the table when its first stream began, so no new "once known" structure is needed. An id with no entry, never observed, still resets immediately with no client created. clientsByAffinity stays bounded by the table, as the earlier design promised.
    2. At connect, id missing (doNetBegin, affinity != 0, client exists). Call clientRoute.metaFlush.accept(traceId) and schedule the existing reconnect signal. Do not reset the pending streams. A later doNetBegin finds the id (new or moved address), connects and sends the queue as usual.
    3. Network close of a connected broker (onNetClosed). Call metaFlush before doNetSignalReconnect, as fetch and produce do. Without it, a reconnect to a broker that has left would keep resolving the stale table entry until the maxAgeMillis timer fires.
    4. client.reconnect = 0. doNetSignalReconnect would call doNetBegin synchronously and loop. With 0, an unknown id keeps today's behaviour: reset pending, no recovery.
    5. Pending streams. They share the client, so they wait together and each retry fires one metaFlush, not one per stream. A caller that aborts or resets its own stream leaves the queue through the existing pending.remove (796-798), and the retry stops when pending is empty. The in-flight stream, if any, is reset by cleanupAppActive as today. clientsByAffinity keeps its entry. Nothing is evicted.

    4. What the caller sees if recovery does not find the id

    Needs your decision. The module has no attempt-count precedent: cache server fetch retries without bound until its callers leave.

    • Option A (recommended). Retry until the existing backoff reaches its cap (50 << attempt >= client.reconnect seconds, about 7 attempts at the 5 s default). If the id is still absent, reset the pending streams with EMPTY_OCTETS, the same reset as today's unknown id, so a caller has one failure shape. It adds no property and no timer. It also covers the case where the route's meta stream has gone and nothing can ever refresh the table. It means resetting reconnectAttempt on a successful connect.
    • Option B. Never reset from the binding. The stream stays unanswered until the id returns or the caller aborts, as for an unreachable broker. A route with no meta stream then hangs forever, and the caller sees nothing.

    If neither fits, say so. I will not add a new timer or property without a decision.

    5. Test plan (test-first; first commit holds only the failing scripts and IT methods)

    Paired client.rpt / server.rpt under specs/binding-kafka.spec, one method per scenario in the existing KafkaCreateTopicsIT classes (spec network and runtime), with no new IT class. Following #3198, network scripts use two accepts as brokers, the meta connection to the bootstrap server and the API connection to the broker.

    • Recovered after refresh. Metadata lists broker 2. A first stream with affinity 2 creates the client and completes. Later Metadata, forced by the flush, drops 2 and then lists it again at another address. The second stream with affinity 2 triggers the flush, and its API connection arrives at the new address.
    • Unrecoverable. Same start, Metadata never lists 2 again. The script asserts that a refresh was requested and no API connection was made. It asserts the outcome chosen in section 4 (reset under A).
    • Unchanged. The affinity-0 and known-id scenarios from feat(binding-kafka): connect an api request stream to the broker named by its affinity #3198 stay as they are. An id never observed still resets with no refresh.

    Runtime ITs use a small client.reconnect so the backoff cap is short.

    What I read, and what I did not

    Read with curl from the Apache Kafka 4.0.0 tag:

    • clients/src/main/resources/common/message/MetadataResponse.json (apiKey 3, versions 0-13): Brokers[] "A list of brokers present in the cluster", NodeId is the map key, with Host and Port. Topics[].Partitions[].LeaderId and the partition ErrorCode are there too.
    • MetadataRequest.json: Topics is nullable from v1.
    • clients/src/main/java/org/apache/kafka/common/protocol/Errors.java: 5 LEADER_NOT_AVAILABLE, 6 NOT_LEADER_OR_FOLLOWER, 8 BROKER_NOT_AVAILABLE, 13 NETWORK_EXCEPTION, 15 COORDINATOR_NOT_AVAILABLE, 16 NOT_COORDINATOR, with their descriptions.

    Not read:

    • The protocol guide page kafka.apache.org/protocol/. I fetched it, but it is a script-rendered shell with no error table, so the error codes come from Errors.java.
    • Any KIP or broker-side text on how a departing broker is removed from Metadata. I take the Metadata response as the cluster's current broker list and nothing more.
    • Zilla's KafkaError.isRetriable flags were read in the repo, not checked against Kafka's own retriable flags.

    Nothing here depends on who calls the stream. It makes the raw API request stream recover the way the fetch and produce clients already do.


    Generated by Claude Code

  2. changed the title [-]binding-kafka: recover when a raw API stream is addressed to a broker id the route no longer knows[/-] [+]binding-kafka: refresh the broker table before answering a raw API stream addressed to an unknown broker id[/+] on Nov 14, 2026
  3. jfallows commented on Nov 14, 2026

    @jfallows
    ContributorAuthor

    Revised design: refresh the broker table, then answer the unknown-id stream with the existing reset

    This replaces my earlier comment, which proposed a retry inside the binding. Paths are under runtime/binding-kafka/src/main/java/io/aklivity/zilla/runtime/binding/kafka/internal/stream/. Line numbers are for develop at 508660f.

    1. Triggering the refresh (mirrors fetch and produce)

    KafkaClientFetchFactory and KafkaClientProduceFactory call clientRoute.metaFlush.accept(traceId) when they learn the table may be stale. KafkaClientApiFactory already takes the same supplyClientRoute, so it calls the same method. A non-zero id that servers does not contain therefore does two things:

    • metaFlush fires, which sends a Metadata request now on each of the route's registered meta streams (KafkaClientMetaFactory.doEncodeRequestIfNecessary);
    • the stream is held, then reset with the existing reset (EMPTY_OCTETS, as today). It is never retried and never connected, even if the refreshed table now contains the id.

    Known ids and affinity 0 are untouched. onNetClosed gets no metaFlush. In fetch and produce that flush serves a connected broker that went away, which is not this scenario, so I leave it out.

    2. Observing that the refresh completed or failed: needs a new mechanism, so I'm asking

    metaFlush is a fire-and-forget LongConsumer fan-out. Nothing in the module observes a refresh finishing:

    • KafkaClientRoute only holds the table and the flush list. It has no completion callback.
    • onDecodeBrokers rewrites servers, and onDecodeMetaResponse bumps nextResponseId. Neither notifies anyone.
    • A flush is skipped when a Metadata request is already in flight (nextRequestId != nextResponseId).
    • A flush reaches nobody when no meta stream is registered on the route.
    • A failed refresh (meta stream aborted, reset or ended) is only visible inside that meta client's cleanupNetwork / onNetwork* paths.

    So "reset only after the refresh completed or failed" cannot be done by the API factory alone. The smallest shape I can find is the reverse direction of the registry that already exists. KafkaClientRoute.registerMetaFlush / metaFlushes (an ArrayUtil list of LongConsumer) is how a meta stream hears the flush. I would add the matching registry for the answer: the API factory registers a one-shot LongConsumer before it flushes, and KafkaMetaClient invokes the route's completion fan-out at the end of a Metadata response (after onDecodeBrokers) and on its failure paths. Questions:

    • Meta streams. With several meta streams on the route, is the first completion enough? The table is route-wide and each response rewrites it, so I propose the first completion or the first failure.
    • Flush skipped because a request is in flight. I would answer on that request's completion. It also rewrites the table, so the table is no staler than the flush would have made it.
    • No meta stream registered. Nothing can refresh. I propose the stream is reset immediately, which is "failed".

    If you would rather not add that registry, the alternatives I see are (a) reset right after firing metaFlush, which does not meet "only after the refresh", or (b) a timer, which would be new and arbitrary. I recommend the registry and will not start until you confirm or redirect.

    3. Several pending streams on the same unknown id

    An unknown id has no KafkaApiClient and no clientsByAffinity entry, as today. The waiting streams are held per KafkaClientApiFactory and route, in a queue that plays the role of KafkaApiClient.pending. The first waiter registers the completion callback and fires one metaFlush. Later waiters only join the queue. On completion or failure the queue is drained and every stream is reset. If a caller aborts or resets its own stream while waiting, it leaves the queue as in pending.remove (796-798). If the queue empties, the callback is dropped.

    The same handling applies where doNetBegin finds the id missing on a reconnect (1819-1830): fire the flush and answer after completion, instead of today's immediate cleanupApp.

    4. clientsByAffinity

    No change. No entry is created for an unknown id (the check stays ahead of computeIfAbsent), so the map stays bounded by the broker table. Entries are never evicted, as before.

    5. Test plan (test-first, first commit holds only the failing scripts)

    Paired client.rpt / server.rpt under specs/binding-kafka.spec, one method per scenario in the existing KafkaCreateTopicsIT classes. The application servers come from #3215.

    • Refresh then reset. The route's meta connection serves Metadata with broker 2, then Metadata without 2. The stream with affinity 2 triggers a second Metadata exchange, and the reset follows it. No API connection is made.
    • Refresh fails. The second Metadata exchange fails (connection closed). The reset still follows, and the stream is not left waiting.
    • Unchanged. Affinity 0 and a known id (the feat(binding-kafka): connect an api request stream to the broker named by its affinity #3198 scripts).

    What I read

    Kafka protocol statements are unchanged from my earlier comment (MetadataResponse.json, MetadataRequest.json, Errors.java at the 4.0.0 tag). This revision adds no new protocol claim. It rests only on the code paths cited above.


    Generated by Claude Code

  4. self-assigned this
    on Nov 14, 2026
  5. added a commit that references this issue on Nov 17, 2026
    bf5ef49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions