Skip to content

binding-kafka: address a raw API request stream to a specific broker by broker id #3195

Closed

Description

@jfallows

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

  1. jfallows commented on Nov 13, 2026

    @jfallows
    ContributorAuthor

    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) and OffsetDeleteResponse.json carry no broker identity; FindCoordinatorResponse.json (apiKey 10, 0-6) has NodeId/Host/Port (v0-3) or Coordinators[] (v4+); MetadataResponse.json (apiKey 3, 0-13) has Brokers[] with NodeId (mapKey), Host, Port.

    Existing mechanism to mirror

    KafkaClientFetchFactory and KafkaClientProduceFactory already address a specific broker this way: the stream's affinity is the broker id (leaderId = begin.affinity()), resolved with clientRoute.servers.get(affinity), where KafkaClientRoute.servers (Long2ObjectHashMap<KafkaServerConfig>, one per resolved route, supplied by KafkaBindingContext.supplyClientRoute) is the id to host/port table that KafkaClientMetaFactory rewrites from the Brokers[] of every Metadata response (onDecodeBrokers). The chosen server becomes the proxy begin extension (ProxyBeginEx inet 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

    • Affinity = broker id, exactly as fetch and produce. clientsByAffinity already keys one KafkaApiClient (so one connection, one pending queue, one learned apiVersionRangeByApiKey) per affinity, so with affinity = broker id that is one connection and one version table per broker with no new structure.
    • Affinity 0 means "no affinity" in the engine and keeps today's behavior: connect to the first bootstrap server (servers.get(0)), as now.
    • Open point (asking the maintainers): broker id 0 is a legal Kafka broker id and collides with "no affinity". Fetch and produce do not hit this because a leader id is always meaningful there. Proposal: an affinity of 0 is always "no broker named", so broker id 0 cannot be addressed by a raw API stream (document it). Alternative, if wanted: reserve a non-zero encoding, but that has no precedent in the module and I would not add it without a decision.

    2. Where the id to address mapping comes from

    • Source: the Metadata Brokers[] that KafkaClientRoute.servers already 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 gets NodeId back and passes it as affinity, so the table only needs to be able to resolve that id.
    • Learned and refreshed by the existing meta stream (each Metadata response replaces the table: clear then putAll). No new cache, no new refresh timer.
    • Resolution happens at connect time, not at client creation: KafkaApiClient resolves servers.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.
    • Id not known when the stream begins: fail immediately, never fall back to another broker (as the issue requires). The stream is reset with the same path an unreachable broker uses today. I do not propose an on-demand Metadata fetch from inside 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

    • One KafkaApiClient per affinity (unchanged) = one connection per broker id, reused by every stream with that affinity, requests serialized through the existing pending queue; opened lazily by the first stream (enqueue then doNetBegin), with the existing reconnect/backoff and idle behaviour. Affinity 0 keeps the single bootstrap connection it has now.
    • The network begin carries the affinity forward (as now) and the proxy extension of the resolved server (as now, from the resolved KafkaServerConfig rather than servers.get(0)).
    • ApiVersions probe, SASL handshake/authenticate run per connection, so per broker (existing flow, unchanged).

    4. Failure cases

    Case Behaviour
    affinity 0 first bootstrap server, as today
    affinity names an id not in the table at begin stream reset (existing error mapping), no connection attempted, no fallback
    id in the table, broker unreachable existing network reset/reconnect path
    broker goes away while connected existing reconnect with backoff; each reconnect re-resolves the id; if it is no longer in the table, the pending streams are reset instead of connecting elsewhere
    table entry changes address next connect uses the new address

    5. Cache pass-through

    Nothing more is needed in the cache bindings: KafkaCacheApiFactory already forwards the caller's affinity to the exit (#3185). Test coverage there only needs a script run through cache_client and cache_server showing 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.rpt under specs/binding-kafka.spec, one IT method each in the existing ITs (no new IT class):

    • Application level (streams/application/api/...), per scenario, with the accept-side affinity option from the engine harness:
      • ...broker : request with a non-zero affinity, expected to reach the exit stream carrying that affinity (extends the existing .affinity shape).
      • no-affinity variant: unchanged (already covered by the plain scenario).
    • Network level (streams/network/api/...), the peers play two brokers:
      • table learned by a Metadata exchange on a meta stream (broker 1 at one address, broker 2 at another), then a raw request with affinity 2 connects to the second broker's address, not the first bootstrap server, and the response comes back;
      • same, no affinity: goes to the first bootstrap server;
      • unknown broker id (not in the Metadata response): stream is reset, no connection to either broker;
      • version-negotiated variant: ApiVersions probe is sent to and answered by the addressed broker, then the request at the negotiated version.
    • Runtime ITs in binding-kafka (existing API IT classes and CacheApiIT for 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

  2. jfallows commented on Nov 13, 2026

    @jfallows
    ContributorAuthor

    Design addendum: client lifecycle and how scripts observe the broker

    Client creation, reuse, close. Today clientsByAffinity only 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:

    • In newStream, affinity 0 goes to the bootstrap client as now. A non-zero affinity is first checked against clientRoute.servers; if the id is absent the stream is rejected before computeIfAbsent, so a stray affinity value cannot grow the map.
    • A known id gets its client lazily on the first stream (one per broker id, reused by later streams through the pending queue; the client owns that broker's ApiVersions table and SASL state).
    • Closing stays as is: the connection closes with the network stream (idle, end, abort, reset) and the client reconnects on the next request, re-resolving the id at that point; if the id has left the table the pending streams are reset. The map entry itself persists, one per broker id that was ever known, which is bounded by the broker table. I do not add eviction, since none exists today and the bound already holds.

    How the scripts observe which broker a stream reached. zilla:affinity on accept and connect cannot assert a per-stream begin affinity, so the network-level scripts use two accepts, one per broker address (two accept URIs on the net side, 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-side option zilla:affinity to send the broker id, as the existing create.topics.v7.affinity scripts do.


    Generated by Claude Code

  3. jfallows commented on Nov 13, 2026

    @jfallows
    ContributorAuthor

    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: KafkaClientFetchFactory and KafkaClientProduceFactory do clientRoute.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):

    Affinity Table knows it Result
    N > 0 yes connect to broker N's host and port
    N > 0 no reset the stream immediately, no client created, no fallback
    0 broker 0 is in the table connect to broker 0
    0 broker 0 is not in the table first bootstrap server (servers.get(0)), as today

    A 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-computeIfAbsent for 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

  4. self-assigned this
    on Nov 13, 2026
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