Repository navigation
Description
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) callsdoKafkaInitialBegin()(:143-156) once per configured topic — the only call site in the file.- That flows into
KafkaCacheBootstrapFactory.KafkaBootstrapStream(.../KafkaCacheBootstrapFactory.java:357+), driving nestedKafkaBootstrapDescribeStream→KafkaBootstrapMetaStream→KafkaBootstrapFetchStreamto populate the cache. - If this fails (e.g.
onDescribeInitialReset,:1045-1055), it's torn down viadoBootstrapCleanup(:660-665) — no signaler, noreconnectAt, no backoff timer anywhere in this file. onAttached/onDetachedonly 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 mmapKafkaCachePartitionand looks up the leader fromcacheRoute.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:
- 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 — mirroringKafkaCacheServerAddressFactory.doKafkaInitialBegin(:143-156). This makes every fetch a potential fresh "member join," the same way every produce request already is. - Complementary: give the bootstrap machinery itself a retry timer analogous to the sibling fanouts'
SIGNAL_RECONNECTpattern —KafkaCacheBootstrapFactory.doBootstrapCleanup(:660-665) and/orKafkaCacheServerAddressFactory.onKafkaReply'sResetFW.TYPE_IDcase (:187-191, currently just callsdoKafkaReplyReset) could instead scheduledoKafkaInitialBegin()again after a backoff, reusing thecontext.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_FAILEDlogged 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 -vshows 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
fix(examples): gate asyncapi.http.kafka.proxy zilla startup on kafka …
fix(examples): gate zilla startup on kafka health across all kafka ex…
feat(binding-openapi,binding-asyncapi): servers subset-selection (#2079)
jfallows commentedon Jul 11, 2026
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 inKafkaCacheBootstrapFactory) send their inner BEGINs withroutedId= the samecache_serverbinding. The engine's genericcontext.streamFactory().newStream(...)dispatches by the begin extension'skindfield through the compositeKafkaCacheServerFactory.newStream()(factories.get(KIND_DESCRIBE|KIND_META|KIND_FETCH)), landing onKafkaCacheServerDescribeFactory/KafkaCacheServerMetaFactory/KafkaCacheServerFetchFactory— the exact same per-topic fanouts that serve regular downstreamcache_clientreads (KafkaCacheServerDescribeFanout, etc., each doing their ownbinding.resolve(...)and keyed viacacheRoute.serverDescribeFanoutsByTopic).Those fanouts already have working
SIGNAL_RECONNECTexponential-backoff retry (reconnectDelay != 0 && !members.isEmpty(), e.g.KafkaCacheServerDescribeFactoryline ~585). Since the bootstrap's own describe/meta/fetch stream registers as a real fanoutmemberand 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 iscache.server.reconnect(default5s), 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 retrybootstrap.reconnect.after.fetch.error— broker resets the bootstrap's fetch connection once (after describe/meta succeed), then accepts on retryBoth pass cleanly with just
cache.server.reconnect=1set (to keep the test fast) — no code changes needed. Pushed asCacheBootstrapIT#shouldReconnectBootstrapAfterDescribeError/#shouldReconnectBootstrapAfterFetchErroronclaude/github-issue-2116-f2i4b4(a65e68fb).What this means
I don't think
KafkaCacheServerAddressFactory/KafkaCacheBootstrapFactoryneed 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 wherebinding.resolve(...)can't resolve the exit at all yet (returnsnull, 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_onaudit mentioned in the issue (that one's inzilla-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
fix(binding-kafka): don't reject cache fetch when partition leader is…
jfallows commentedon Jul 11, 2026
Follow-up with the actual, concrete bug — narrower and different from my previous comment's speculation, but confirmed by test.
The real gap
KafkaCacheClientFetchFactory.onClientInitialBeginandKafkaCacheServerFetchFactory.onServerInitialBeginboth reject an incoming fetch stream immediately (ERROR_NOT_LEADER_FOR_PARTITION) whenever the caller's declaredaffinitydoesn't matchcacheRoute.supplyLeadersByPartitionId(topic).get(partitionId)— a per-topic map populated by the meta fanout, backed by anInt2IntHashMap(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/unsetaffinitycan never equal that sentinel, the check fails and the stream is torn down immediately, at both thecache_client-facing layer and the downstreamcache_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 plaincache_clientfetch request with no prior meta lookup gets torn down before the request even reaches the exit binding.Fix
Pushed in
884ef385(branchclaude/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_RECONNECTreconnect (verified with two newCacheBootstrapITtests, 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
jfallows commentedon Jul 11, 2026
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 ownsKafkaCacheRoute/leadersByPartitionId, keyed by the resolvedcache_serverbinding id) is a freshLong2ObjectHashMap<>()created inKafkaBindingContext's constructor, and that constructor runs once per worker viaKafkaBinding.supply(EngineContext). Whether a binding is replicated across workers is governed byBinding.workers(KindConfig):cache_client(ownsKafkaCacheClientFetchFactory) returns the defaultInteger.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 return1— pinned to exactly one worker (per the SPI doc comment:"for bindings that maintain global ordered state").So there is one
leadersByPartitionIdmap per worker, and only the single worker hostingcache_serverever gets bootstrap-driven population, since bootstrap is triggered from that binding's ownonAttachedand 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 thecache_clientbinding on that specific worker (populated viaKafkaCacheClientMetaFactory, a distinct per-worker fanout that mirrors the server-side data back over a real stream).What this means concretely
clear()'d and immediately refilled atomically within the same call when new meta data arrives (checked bothKafkaCacheServerMetaFactoryandKafkaCacheClientMetaFactory) — never wiped on disconnect/reconnect. A later fetch on that same worker for that same partition won't hit this again.options.bootstrapis 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 hostingcache_serverwould always be rejected, since that worker's own map was never touched by bootstrap at all.leadersByPartitionIdonly 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) / workersof 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
fix(binding-kafka): don't reject cache fetch when partition leader is…
fix(binding-kafka): don't reject cache fetch when partition leader is…