Skip to content

binding-kafka: cache-client fetch never recovers if the one-shot startup bootstrap fails #2116

Closed

Description

@jfallows

Summary

binding-kafka's local-cache read path (kind: cache_client, e.g. serving Kafka Fetch on behalf of an HTTP/asyncapi GET) is populated by a one-shot startup bootstrap stream with no retry. If that bootstrap fails once — e.g. because the Kafka broker isn't ready yet when Zilla starts, a real and common race in docker compose up where no depends_on: condition: service_healthy gates Zilla on Kafka — the topic's local cache is permanently abandoned, and every future fetch for that topic/partition hangs forever with zero retry.

This was found while diagnosing a CI flake on testing (asyncapi.http.kafka.proxy) in #2079 (unrelated PR — the example itself, and the code changed in that PR, are not the cause). Reproduced locally and traced to root cause; see mechanism below. The example's own flake was mitigated in #2079 by adding depends_on: kafka: condition: service_healthy to that one example's compose.yaml, but that's a docker-compose workaround, not a fix — the same race is possible any time the broker is briefly unavailable at Zilla startup (or restarts later), and 18 of our example configs have this same depends_on gap.

Root cause (traced, not guessed)

The asymmetry between Kafka produce (self-heals) and Kafka fetch/cache_client (does not) is architectural:

  • Produce self-heals because every inbound request (e.g. an HTTP POST) creates a fresh KafkaCacheServerProduceStream, which joins the produce fanout as a new member on arrival — unconditionally attempting to (re)connect regardless of the fanout's prior state. So the next request after a broker outage is the retry, and it succeeds once the broker is back.
  • Fetch does not self-heal. The topic/partition/leader metadata behind the local mmap cache is proactively bootstrapped exactly once, at binding-attach time, from options.bootstrap:
    • KafkaCacheServerAddressFactory.onAttached (runtime/binding-kafka/.../stream/KafkaCacheServerAddressFactory.java:80-96) calls doKafkaInitialBegin() (:143-156) once per configured topic — the only call site in the file.
    • That flows into KafkaCacheBootstrapFactory.KafkaBootstrapStream (.../KafkaCacheBootstrapFactory.java:357+), driving nested KafkaBootstrapDescribeStream → KafkaBootstrapMetaStream → KafkaBootstrapFetchStream to populate the cache.
    • If this fails (e.g. onDescribeInitialReset, :1045-1055), it's torn down via doBootstrapCleanup (:660-665) — no signaler, no reconnectAt, no backoff timer anywhere in this file.
    • onAttached/onDetached only fire on binding attach/detach (config reload) — never on request traffic, so nothing ever re-triggers bootstrap.
    • KafkaCacheClientFetchFactory.newStream (.../KafkaCacheClientFetchFactory.java:177-266) never itself makes a network connection — it purely reads the shared mmap KafkaCachePartition and looks up the leader from cacheRoute.supplyLeadersByPartitionId(topicName) (:247-248). If that map was never populated, the fetch stream just waits on the fanout for data that will never arrive.

Notably, the sibling server-side fanouts (KafkaCacheServerDescribeFactory, KafkaCacheServerMetaFactory, KafkaCacheServerFetchFactory) already implement real exponential-backoff reconnect via SIGNAL_RECONNECT (default cache.server.reconnect = 5s, see KafkaConfiguration.java:118, e.g. KafkaCacheServerDescribeFactory.onDescribeFanoutInitialReset :572-611) — but that retry is gated on !members.isEmpty(), and the bootstrap stream is a one-shot, non-member caller, so it never benefits from this existing mechanism.

Suggested fix

Two complementary changes:

  1. Primary: KafkaCacheClientFetchFactory.newStream (:177-266, specifically the fanout/leader-lookup block :218-262) should trigger its own on-demand describe/meta bootstrap when the leader map has no entry for the requested partition, rather than relying solely on the binding-attach-time bootstrap — mirroring KafkaCacheServerAddressFactory.doKafkaInitialBegin (:143-156). This makes every fetch a potential fresh "member join," the same way every produce request already is.
  2. Complementary: give the bootstrap machinery itself a retry timer analogous to the sibling fanouts' SIGNAL_RECONNECT pattern — KafkaCacheBootstrapFactory.doBootstrapCleanup (:660-665) and/or KafkaCacheServerAddressFactory.onKafkaReply's ResetFW.TYPE_ID case (:187-191, currently just calls doKafkaReplyReset) could instead schedule doKafkaInitialBegin() again after a backoff, reusing the context.signaler() already available in the class.

Separately, worth auditing/fixing the 18 example compose.yaml files that lack depends_on: kafka: condition: service_healthy on the zilla service (only a mitigation for the startup case, not the general fix, but cheap and reduces CI flakiness in the meantime).

Reproduction

In a docker-compose stack with Zilla racing ahead of Kafka's own readiness (no depends_on gate), roughly 1 in 4-5 fresh container starts:

  • BINDING_KAFKA_BROKER_CONNECTION_FAILED logged 2-3 times at Zilla startup (before Kafka is truly ready)
  • A subsequent produce request (e.g. HTTP POST → Kafka produce) succeeds fine once Kafka is up
  • A subsequent fetch request (e.g. HTTP GET → Kafka cache read) hangs forever — zilla dump -v shows zero new stream frames for that request; the topic's cache was never populated and nothing ever retries

Per this repo's test-first discipline, a fix should include an IT that starts a cache_client binding against a broker that becomes available only after the binding's initial bootstrap attempt has failed, and asserts a subsequent fetch eventually succeeds (rather than hanging indefinitely).

Activity

  1. jfallows commented on Jul 11, 2026

    @jfallows
    ContributorAuthor

    Traced this end-to-end and I don't think the stated root cause holds against current develop — the bootstrap's describe/meta/fetch streams already inherit the sibling fanouts' reconnect logic, and I've added regression tests proving it. Details:

    Dispatch trace

    KafkaBootstrapDescribeStream / KafkaBootstrapMetaStream / KafkaBootstrapFetchStream (all in KafkaCacheBootstrapFactory) send their inner BEGINs with routedId = the same cache_server binding. The engine's generic context.streamFactory().newStream(...) dispatches by the begin extension's kind field through the composite KafkaCacheServerFactory.newStream() (factories.get(KIND_DESCRIBE|KIND_META|KIND_FETCH)), landing on KafkaCacheServerDescribeFactory / KafkaCacheServerMetaFactory / KafkaCacheServerFetchFactory — the exact same per-topic fanouts that serve regular downstream cache_client reads (KafkaCacheServerDescribeFanout, etc., each doing their own binding.resolve(...) and keyed via cacheRoute.serverDescribeFanoutsByTopic).

    Those fanouts already have working SIGNAL_RECONNECT exponential-backoff retry (reconnectDelay != 0 && !members.isEmpty(), e.g. KafkaCacheServerDescribeFactory line ~585). Since the bootstrap's own describe/meta/fetch stream registers as a real fanout member and never voluntarily detaches, members.isEmpty() never goes true, so the fanout just keeps retrying with backoff in the background and delivers fresh data to the bootstrap member whenever the broker recovers — this is cache.server.reconnect (default 5s), not a separate/missing mechanism.

    Empirical verification

    I wrote two new k3po scenarios and ran them against completely unmodified develop (no production code changes):

    • bootstrap.reconnect.after.describe.error — broker resets the bootstrap's describe connection once, then accepts on retry
    • bootstrap.reconnect.after.fetch.error — broker resets the bootstrap's fetch connection once (after describe/meta succeed), then accepts on retry

    Both pass cleanly with just cache.server.reconnect=1 set (to keep the test fast) — no code changes needed. Pushed as CacheBootstrapIT#shouldReconnectBootstrapAfterDescribeError / #shouldReconnectBootstrapAfterFetchError on claude/github-issue-2116-f2i4b4 (a65e68fb).

    What this means

    I don't think KafkaCacheServerAddressFactory/KafkaCacheBootstrapFactory need their own retry timer — that would duplicate logic that's already there and already working, gated on the exact same config knob the sibling fanouts use. If the CI flake in #2079 (or the field reports motivating this issue) are real, I'd guess the actual gap is narrower than described — e.g. a first-attach race where binding.resolve(...) can't resolve the exit at all yet (returns null, so no fanout/member is ever created, meaning the reconnect logic never gets a chance to run), or something specific to how a raw TCP connection failure (vs. an explicit protocol-level RESET) propagates up through the Kafka client stack — rather than "bootstrap has no reconnect at all."

    Happy to dig into either of those narrower hypotheses, or into the docker-compose depends_on audit mentioned in the issue (that one's in zilla-examples, which I don't have access to from this session), if that's still wanted — but wanted to flag this before spending more effort building a retry mechanism that duplicates something that already exists and already passes.


    Generated by Claude Code

  2. jfallows commented on Jul 11, 2026

    @jfallows
    ContributorAuthor

    Follow-up with the actual, concrete bug — narrower and different from my previous comment's speculation, but confirmed by test.

    The real gap

    KafkaCacheClientFetchFactory.onClientInitialBegin and KafkaCacheServerFetchFactory.onServerInitialBegin both reject an incoming fetch stream immediately (ERROR_NOT_LEADER_FOR_PARTITION) whenever the caller's declared affinity doesn't match cacheRoute.supplyLeadersByPartitionId(topic).get(partitionId) — a per-topic map populated by the meta fanout, backed by an Int2IntHashMap(Integer.MIN_VALUE) that starts empty.

    A fetch request that arrives before any describe/meta has ever resolved that partition's leader — exactly the startup race this issue describes — reads the "missing" sentinel (Integer.MIN_VALUE) back from that lookup. Since a caller's default/unset affinity can never equal that sentinel, the check fails and the stream is torn down immediately, at both the cache_client-facing layer and the downstream cache_server-facing layer. This is a one-shot, point-in-time gate — it never waits or retries once the leader becomes known moments later.

    I reproduced this with a k3po scenario (client.races.ahead.of.leader, CacheFetchIT#shouldServeClientFetchThatRacesAheadOfLeader): a plain cache_client fetch request with no prior meta lookup gets torn down before the request even reaches the exit binding.

    Fix

    Pushed in 884ef385 (branch claude/github-issue-2116-f2i4b4): both factories now track whether the leader lookup actually resolved an entry (leaderKnown) versus returned the "missing" sentinel, and only reject on a known-but-different leader (a genuine partition reassignment) — not on "not resolved yet." When unknown, the stream just joins the fanout and waits, the same way it already does once the leader resolves.

    Verified with the full existing leader-mismatch/reconnect coverage (CacheFetchIT, CacheMergedIT, CacheProduceIT, CacheDescribeIT, CacheMetaIT, CacheBootstrapIT — 172 tests) — all green, so genuine leader-reassignment rejection still works as before.

    Correction to my earlier comment

    I'd previously concluded no fix was needed because the bootstrap's describe/meta/fetch streams already inherit the sibling fanouts' SIGNAL_RECONNECT reconnect (verified with two new CacheBootstrapIT tests, also in this push) — that part still holds and no code changes were needed there. But this fetch-layer check is a separate, real gap sitting one level below all of that: even with the connection-level reconnect working perfectly, a fetch request that happens to arrive before the leader is known gets permanently rejected rather than waiting, regardless of how quickly the underlying broker connection recovers. That's the piece actually matching "every future fetch for that topic/partition hangs" (or, more precisely, fails outright) in the original report.


    Generated by Claude Code

  3. jfallows commented on Jul 11, 2026

    @jfallows
    ContributorAuthor

    Additional detail worth recording: the leader-unknown gap described above isn't just a narrow, one-shot startup race — it's structurally per-worker, which likely explains the "roughly 1 in 4-5" reproduction rate better than pure timing jitter.

    Why this is per-worker, not global

    KafkaBindingContext.cacheRoutesById (which owns KafkaCacheRoute/leadersByPartitionId, keyed by the resolved cache_server binding id) is a fresh Long2ObjectHashMap<>() created in KafkaBindingContext's constructor, and that constructor runs once per worker via KafkaBinding.supply(EngineContext). Whether a binding is replicated across workers is governed by Binding.workers(KindConfig):

    • cache_client (owns KafkaCacheClientFetchFactory) returns the default Integer.MAX_VALUE — no constraint, so it's instantiated independently on every worker.
    • cache_server (owns bootstrap, the meta fanout, and the local cache) overrides this to return 1 — pinned to exactly one worker (per the SPI doc comment: "for bindings that maintain global ordered state").

    So there is one leadersByPartitionId map per worker, and only the single worker hosting cache_server ever gets bootstrap-driven population, since bootstrap is triggered from that binding's own onAttached and can only ever run on that one pinned worker. Every other worker's copy of the map stays at the "missing" sentinel indefinitely, unless something separately drives an explicit client-side describe+meta request through the cache_client binding on that specific worker (populated via KafkaCacheClientMetaFactory, a distinct per-worker fanout that mirrors the server-side data back over a real stream).

    What this means concretely

    1. Same worker, same partition, no repartition — once that worker's copy resolves a partition's leader, it stays resolved. The map is only ever clear()'d and immediately refilled atomically within the same call when new meta data arrives (checked both KafkaCacheServerMetaFactory and KafkaCacheClientMetaFactory) — never wiped on disconnect/reconnect. A later fetch on that same worker for that same partition won't hit this again.
    2. A different worker — still broken pre-fix, regardless of how many times meta has already succeeded elsewhere. A bare fetch that skips its own meta lookup — which is exactly the optimization options.bootstrap is meant to enable, trusting the pre-warmed cache instead of paying a describe+meta round trip per request — landing on any worker other than the one hosting cache_server would always be rejected, since that worker's own map was never touched by bootstrap at all.
    3. A newly-added partition on an already-resolved topic (repartition) — still broken pre-fix even on the "good" worker, since leadersByPartitionId only reflects whatever partitions were present in the last meta snapshot.

    So for any deployment with more than one worker (default is one per CPU core), this plausibly affects (workers − 1) / workers of bootstrap-reliant fetch traffic — worker-count-shaped, not just a narrow window at startup. That fits "roughly 1 in 4-5 fresh container starts" well if the test environment had ~4-5 workers/cores.


    Generated by Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    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