Repository navigation
Description
Problem
Raw Kafka API request streams (KIND_API_REQUEST, KafkaApiRequestBeginEx) are served by KafkaClientApiFactory. Its KafkaApiClient always connects to the first configured bootstrap server (servers.get(0)); the stream's affinity only selects which client instance is used (clientsByAffinity), never which broker it connects to (read on develop at 5556779 and on the restacked pass-through; not run against a multi-broker cluster).
Some Kafka APIs are broker-specific: the request names no broker (for example OffsetDelete, API key 47, carries only GroupId, Topics[].Name and Topics[].Partitions[].PartitionIndex) but must be sent on a connection to a particular broker (the group coordinator). A client first discovers that broker, for example with FindCoordinator, whose response carries the broker's NodeId, Host and Port (v0 to v3; Coordinators[] from v4), and the general mapping from broker id to address is the Brokers[] of a Metadata response (NodeId, Host, Port, Rack). Today a raw API stream cannot reach the broker that discovery names: it goes to the first bootstrap server, which is the right broker only on a single-broker cluster or by chance, and otherwise gets an error such as NOT_COORDINATOR (16) from the broker.
For APIs that do not need a specific broker, any bootstrap server remains right.
Expected
- A raw API request stream can be addressed to a specific broker by broker id, carried as the stream's affinity (the identifier the binding already uses to select a client instance), and the client binding connects to that broker.
- The binding learns the mapping from broker id to host and port. The source of that mapping (the Metadata brokers list, the host and port in a FindCoordinator response, or both) and whether the binding keeps a cached broker table is decided in this issue's design.
- A stream with no broker affinity behaves as today (any bootstrap server).
- An affinity that names no known broker fails the stream cleanly, as an unreachable broker does today (reset with the existing error mapping), without falling back to another broker.
Design first
Before implementing, post a design on this issue: how affinity encodes a broker id (and how that coexists with the uses of affinity that select a client instance today), where the id-to-address mapping comes from and when it is refreshed (including a broker id that is not yet known when a stream begins), how the client binding opens and reuses connections per broker (the existing KafkaClientApiFactory and the other client factories that connect to specific brokers, for example the group, offset fetch and offset commit clients that take host and port in their begin extensions), the failure cases, and what the cache pass-through must do (it already forwards the caller's affinity to the exit). The pattern to mirror must be an existing implementation in the same module; if none fits, ask before inventing one.
Test plan (test-first)
After the design is accepted: paired client.rpt and server.rpt scripts under specs/binding-kafka.spec for a raw API request addressed to a broker other than the first bootstrap server (the script peers play two brokers), a stream with no broker affinity (first bootstrap server, as today), an unknown broker id, and the version-negotiated variant, with the spec ITs and the runtime ITs in binding-kafka. The first commit contains the failing scripts.
Notes
Protocol facts above are from the Apache Kafka message definitions (OffsetDeleteRequest.json, OffsetDeleteResponse.json, FindCoordinatorResponse.json, MetadataResponse.json at the 4.0.0 tag).
Activity
jfallows commentedon Nov 13, 2026
Design: address a raw API request stream to a broker by broker id
Protocol facts re-read from the Apache Kafka 4.0.0 tag (
clients/src/main/resources/common/message/):OffsetDeleteRequest.json(apiKey 47, validVersions 0) andOffsetDeleteResponse.jsoncarry no broker identity;FindCoordinatorResponse.json(apiKey 10, 0-6) hasNodeId/Host/Port(v0-3) orCoordinators[](v4+);MetadataResponse.json(apiKey 3, 0-13) hasBrokers[]withNodeId(mapKey),Host,Port.Existing mechanism to mirror
KafkaClientFetchFactoryandKafkaClientProduceFactoryalready address a specific broker this way: the stream's affinity is the broker id (leaderId = begin.affinity()), resolved withclientRoute.servers.get(affinity), whereKafkaClientRoute.servers(Long2ObjectHashMap<KafkaServerConfig>, one per resolved route, supplied byKafkaBindingContext.supplyClientRoute) is the id to host/port table thatKafkaClientMetaFactoryrewrites from theBrokers[]of every Metadata response (onDecodeBrokers). The chosen server becomes the proxy begin extension (ProxyBeginExinet destination/authority) on the network stream. The group, offset fetch and offset commit clients instead take host and port in their begin extensions (offset fetch even carries// TODO: use affinity (like meta, fetch, produce) instead of host and port), which the issue already rules out. Fetch and produce are therefore the established pattern, and nothing new is invented.1. Carrying the broker id
clientsByAffinityalready keys oneKafkaApiClient(so one connection, one pending queue, one learnedapiVersionRangeByApiKey) per affinity, so with affinity = broker id that is one connection and one version table per broker with no new structure.servers.get(0)), as now.2. Where the id to address mapping comes from
Brokers[]thatKafkaClientRoute.serversalready holds. A FindCoordinator response also carries host and port, but a raw API stream is opaque bytes to the binding; decoding responses of arbitrary APIs to harvest addresses would be a new mechanism with no precedent. The caller that runs FindCoordinator already getsNodeIdback and passes it as affinity, so the table only needs to be able to resolve that id.clearthenputAll). No new cache, no new refresh timer.KafkaApiClientresolvesservers.get(affinity)each time it opens the network stream (first connect and every reconnect), so a changed address or a broker that left is picked up on the next connect instead of staying pinned to the address first seen.KafkaClientApiFactory: that would be a new internal meta client with no counterpart in the module (fetch and produce also expect the table to be populated by the meta stream). Whether the table is populated for a route is a precondition on the caller (a meta stream on the route), same as fetch and produce.3. Connections: open, reuse, close
KafkaApiClientper affinity (unchanged) = one connection per broker id, reused by every stream with that affinity, requests serialized through the existingpendingqueue; opened lazily by the first stream (enqueuethendoNetBegin), with the existing reconnect/backoff and idle behaviour. Affinity 0 keeps the single bootstrap connection it has now.KafkaServerConfigrather thanservers.get(0)).4. Failure cases
5. Cache pass-through
Nothing more is needed in the cache bindings:
KafkaCacheApiFactoryalready forwards the caller's affinity to the exit (#3185). Test coverage there only needs a script run throughcache_clientandcache_servershowing the broker-id affinity arrives unchanged at the exit (the plain affinity scenario already proves the forwarding).6. Test plan (test-first; first commit has only failing scripts and IT methods)
Paired
client.rpt/server.rptunderspecs/binding-kafka.spec, one IT method each in the existing ITs (no new IT class):streams/application/api/...), per scenario, with the accept-sideaffinityoption from the engine harness:...broker: request with a non-zero affinity, expected to reach the exit stream carrying that affinity (extends the existing.affinityshape).streams/network/api/...), the peers play two brokers:binding-kafka(existing API IT classes andCacheApiITfor the pass-through), configs with two server addresses so the second broker is a different port.Nothing in this design depends on who the caller of the stream is; it only gives the raw API request stream the same affinity-as-broker-id contract fetch and produce already have.
Generated by Claude Code
jfallows commentedon Nov 13, 2026
Design addendum: client lifecycle and how scripts observe the broker
Client creation, reuse, close. Today
clientsByAffinityonly ever adds (computeIfAbsent, never removed): a client's connection ends on network end/abort/reset and reconnects on demand, but the map entry stays. With broker-id affinity that is bounded by the cluster size only if an unknown id never creates an entry. So:newStream, affinity 0 goes to the bootstrap client as now. A non-zero affinity is first checked againstclientRoute.servers; if the id is absent the stream is rejected beforecomputeIfAbsent, so a stray affinity value cannot grow the map.pendingqueue; the client owns that broker's ApiVersions table and SASL state).How the scripts observe which broker a stream reached.
zilla:affinityon accept and connect cannot assert a per-stream begin affinity, so the network-level scripts use two accepts, one per broker address (twoacceptURIs on thenetside, each scripted as one broker). Reaching the right broker is observed by which accept receives the connection and the request bytes; the wrong broker's accept never being connected to is asserted by it staying unmatched (the IT completes only if only the addressed accept ran). The application-level scripts use the connect-sideoption zilla:affinityto send the broker id, as the existingcreate.topics.v7.affinityscripts do.Generated by Claude Code
jfallows commentedon Nov 13, 2026
Revised design: affinity is always the broker id, including 0
This replaces the "affinity 0 means no broker named" proposal of section 1 above. Checked against the code:
KafkaClientFetchFactoryandKafkaClientProduceFactorydoclientRoute.servers.get(affinity)with the affinity used directly as the broker id, so there is no "no affinity" meaning in those factories and affinity 0 simply is broker 0. Classic clusters number brokers from 0, so treating 0 as unaddressed would leave a coordinator on broker 0 unreachable, which is the case this issue exists for.Resolution for a raw API request stream (
KafkaClientApiFactory, at each connect):servers.get(0)), as todayA caller that wants any broker (affinity 0) gets broker 0 when it is known; a caller that wants broker 0 gets it; a caller that wants N > 0 gets N or a reset.
One behaviour change. Today every API stream with affinity 0 connects to the first bootstrap server. After this change, an affinity-0 stream connects to broker 0's advertised address when the route's meta stream has already learned broker 0, which can differ from the bootstrap address (advertised versus bootstrap listener). Routes with no populated table, or whose table lacks broker 0, behave exactly as today. This is the same assumption fetch and produce already make: the advertised addresses in the table are reachable from the binding. For APIs that need no specific broker, broker 0 is as valid a target as any bootstrap server.
Remaining edge. A caller that wants broker 0 before the table has learned broker 0 is sent to the first bootstrap server (same dependency on the table being populated as fetch and produce). An unknown non-zero id still resets, as decided.
Everything else in the design (table source, per-connect resolution, one client per affinity, reject-before-
computeIfAbsentfor an unknown non-zero id, close behaviour, failure table, test plan) is unchanged, with two test additions: an affinity-0 stream with the table containing broker 0 reaches broker 0's accept; an affinity-0 stream with a table lacking broker 0 reaches the first bootstrap server's accept.Generated by Claude Code