DEV Community

Mostafa Tavassoli
Mostafa Tavassoli

Posted on

What happens when a 40-second LLM call outlives Kafka's 30-second lock

Kafka 4.2 made share groups production-ready: queue-style consumption where several consumers take records from the same partitions. Each record is locked to one consumer while it works on it. The default lock is 30 seconds.

Now put an AI agent behind that consumer. One event means a model call, maybe a tool call or two, maybe a retry. Forty seconds is not unusual.

So what happens when the agent is still thinking when the lock expires?

I measured it. Short version: the same event is processed again, up to five times, and every side effect it triggers can happen again. The fixes that work are not the ones I expected, and one framework's built-in fix did not hold.

Why this matters for agents

Classic Kafka consumers are fast: milliseconds per record. A 30-second lock is generous for them. Agents break that assumption:

  • Model latency varies a lot, and the tail is long.
  • Agents call tools, and tools have side effects: create a ticket, send an email, issue a refund.
  • An agent that runs twice on the same event does not just waste tokens. It can act twice.

In share groups, a record whose lock expires is delivered again to the next available consumer, with an increasing delivery count, up to a delivery limit (5 by default). That is correct queue behavior. It is just bad news when one delivery takes longer than the lock.

The experiment

I built this into Streamjack, an open-source harness I'm writing that tests AI agents consuming and producing Kafka events. The test runs on a disposable Kafka 4.2.1 broker with two simulated agent instances in one share group. Each record takes 3 seconds of "thinking" and then triggers one side effect. Timings are scaled down (a 2-second lock instead of 30) so the test runs in seconds; the ratio is the same.

Case Lock Deliveries Side effects
Processing blocks the consumer thread 2 s 5 5
Same, plus deduplication of the side effect 2 s 5 1
Lock longer than processing 6 s 1 1
Lock renewed from a free consumer thread while working 3 s (4.5 s of work) 1 1

It runs in CI on every commit, and each case also asserts that processing finished before the deadline and that exactly one acknowledgement succeeded where the record is delivered once.

Three things I learned

1. Deduplication fixes the side effects, not the work.
With an idempotency key on the side effect, the duplicate actions disappear. But the model still ran five times. For an LLM agent that is five times the cost and latency, and five chances for a non-deterministic model to decide something different.

2. A longer lock works, if you know your worst case.
The broker caps the lock (group.share.max.record.lock.duration.ms, 60 seconds by default). If your agent's p99.9 is above the cap, you cannot configure your way out.

3. Renewal works, but only from a thread that is free to renew.
Kafka 4.2 lets a consumer extend the lock with AcknowledgeType.RENEW. The catch: KafkaShareConsumer is not thread-safe, so the thread that talks to Kafka must stay free while another thread does the slow work:

CompletableFuture<Void> task = CompletableFuture.runAsync(() -> slowWork(work));
while (!task.isDone()) {
    Thread.sleep(lock.toMillis() / 4);
    if (task.isDone()) break;
    consumer.acknowledge(current, AcknowledgeType.RENEW);
    consumer.commitSync();
    // The renewed record comes back through a later poll(); acknowledge that copy from now on.
    current = pollFor(consumer, current);
}
consumer.acknowledge(current, AcknowledgeType.ACCEPT);
consumer.commitSync();
Enter fullscreen mode Exit fullscreen mode

A simple poll loop that does the work inline can never renew. That is exactly the "5 deliveries, 5 side effects" row.

What about frameworks?

You would expect your messaging framework to handle renewal. It depends.

  • Spring for Apache Kafka 4.2 has setShareAutoRenewLocks(true). It is off by default.
  • SmallRye Reactive Messaging (the Kafka connector behind Quarkus) renews automatically. In my experiments, with processing slower than the lock, the renewal did not keep the lock: the record was delivered again with an increasing delivery count, and a later record was acknowledged by the broker but never reached the handler. In the scaled-down runs, renewal also failed at every interval afterwards.

With SmallRye's default settings (30-second lock, renewal checked every 5 seconds) and a 40-second simulated model call, the first event was analyzed twice, and the next event still had not reached the agent 150 seconds later.

I reproduced this on Quarkus 3.40 and on a Quarkus 4 release candidate, built a minimal reproducer that also fails on GitHub Actions, and reported it upstream. The root cause is not confirmed yet, so treat this as "test it in your setup", not "this framework is broken".

One more detail from the reproducer: with a very short lock, even a fast handler was sometimes redelivered, apparently because renewal is timed from when the connector received the record. With default settings, renewal starts about 25 seconds in, so this mainly hits slow handlers. Like agents.

What I'd do

  1. Make side effects idempotent in application code. It was the only control that held in every case, including the framework issue. Not in the prompt: in code, keyed by the business id.
  2. Size the lock for your worst-case latency, within the broker's cap. Measure the tail, not the average.
  3. If you rely on renewal, test it with a handler that is slower than the lock. Check the delivery count, and check that the next record is still processed.

The general lesson is older than share groups: an at-least-once system will deliver twice, and an agent that acts must be safe to run twice. LLM latency just makes "twice" much more likely.


The tests, the opt-in framework experiments, and a longer write-up are in Streamjack. There is also a browser demo of the agent attacks Streamjack tests for.

Top comments (13)

Collapse
 
iictp profile image
IICTP •

The experiment table is what makes this land — especially case 2, where the same 2-second lock still delivered five times but dedup cut the side effects to one, versus case 4, where renewing from a free thread got it to one delivery and one side effect. That split between fixing the work and fixing the effects is the part I'd keep. Did the SmallRye bug report get any upstream response yet, or is the workaround still to keep the lock longer than the call?

Collapse
 
mostavassoli profile image
Mostafa Tavassoli •

Thanks! Yes, that split between fixing the work and fixing the effects is the main takeaway for me too.

No response from the SmallRye maintainers yet. Since the post I narrowed it down a bit more: a record still counts as "in progress" until its acknowledgement is committed, which can be a second or two after the handler finishes, and the renewal timer can fire in that window. Timeline and details here: github.com/smallrye/smallrye-react...

Until there's a fix, I wouldn't rely on the connector's renewal for slow handlers. Options:

  • Keep the lock above your worst-case call so renewal never kicks in. The broker caps it at 60 s by default (group.share.max.record.lock.duration.ms, which you can raise on your own cluster), and SmallRye's share-group.unprocessed-record-max-age.ms (also 60 s by default) has to be above the call time too.
  • Or use the plain share consumer and renew from a thread that isn't doing the work, like case 4.

Either way, keep the side effect idempotent. Sara's lease idea below also helps with the duplicate model calls.

Collapse
 
iictp profile image
IICTP •

Thank you for narrowing it down further — that ack-commit window, where a record still counts as 'in progress' for a second or two after the handler finishes, is exactly the kind of detail that explains the stray redeliveries. Until the fix lands, keeping the lock above the worst-case call feels like the pragmatic option, since it sidesteps renewal entirely. For a brand-new service, would you go with the plain share consumer and renew from a separate thread, or is the bigger lock the simpler default you'd reach for first?

Thread Thread
 
mostavassoli profile image
Mostafa Tavassoli •

For a new service I'd start with the bigger lock. It has no moving parts: measure the tail of the model call (p99.9, not the average), keep the lock above it with some margin, make the side effects idempotent, and alert on deliveryCount > 1 so you know when the tail grows past it.

I'd only reach for renewal on a separate thread if the calls can run longer than the broker's cap. It works (case 4), but it's more code to get right: the consumer isn't thread-safe, and the renewed record comes back through a later poll, so you have to ack that copy.

If the calls can take minutes, I'd step back and not hold the Kafka lock during the model call at all: write the event to your own work store, ack it right away, and process it with your own lease, a bit like Sara's idea. Kafka stays fast, and the slow part has its own retries.

And an update on the bug: a SmallRye maintainer confirmed it this morning and is working on a fix.

Collapse
 
userxnom profile image
Abdullah Naseer •

The experiment table is the whole post for me — "5 deliveries, 5 side effects" versus "5 deliveries, 1 side effect" with deduplication makes the real lesson impossible to miss: idempotency fixes the damage, not the wasted work. The model still ran five times, and the tokens still burned.

The part I respect most is the SmallRye finding. Reporting it upstream while the root cause is still unconfirmed, and framing it as "test it in your setup" rather than a verdict, is exactly how a reproducer should be shared. And the thread-safety catch is the trap most teams would walk into: renewal only works from a thread that is free to renew, so the obvious inline poll loop can never renew at all.

One question about the most surprising detail: with a very short lock, even a fast handler was sometimes redelivered. Do you have a suspicion about what is happening there — is the lock clock starting before the handler even receives the record, or is it more like a race between delivery and the first renewal check?

Collapse
 
mostavassoli profile image
Mostafa Tavassoli •

Good question! I think it's a bit of both.

Your first guess is right: the clock starts before the handler sees the record. Kafka starts the lock when the broker hands the record to the consumer, and SmallRye seems to time its renewal from then too. With a 2 s lock, the first renewal check comes about 1.5 s after the consumer gets the record.

And your second guess is where I think it actually breaks. A 0.5 s handler usually finishes before that check, and those runs were fine. It only failed sometimes, probably when the handler started late and was still running when renewal kicked in. Every time it failed, I saw the same renewal errors as in the slow case. With a 10 s lock, where renewal never starts, it ran exactly once every time.

So my suspicion is that something goes wrong once renewal starts, and the short lock just makes that more likely to happen with a fast handler. I haven't confirmed exactly what yet; that's what the issue is for.

Collapse
 
mostavassoli profile image
Mostafa Tavassoli •

You got me curious, so I measured it. Your second guess was basically right: a record counts as "in progress" until its acknowledgement is committed, which can be 1–2 s after the handler finishes. With a short lock, the renewal timer fires inside that gap, and the same delivery got handed to the handler again. Details and timestamps here: github.com/smallrye/smallrye-react...

Collapse
 
delayrun profile image
delay.run •

What happens on delivery 5 is the part I'd want an alert on. Once the delivery limit is reached the record gets archived and the group moves on, so an agent whose tail latency sits above the lock cap doesn't just do the work five times, it can end up with nothing done and no error anywhere. Graphing delivery count (anything above 1 means a lock expired) gives you warning long before that point. In the 40-second SmallRye run, did any records actually reach the limit, or did it stall before that?

Collapse
 
mostavassoli profile image
Mostafa Tavassoli •

Yeah, that's the nasty part. After the 5th delivery the record gets archived and the group just moves on, so you can pay for the work five times and still have nothing to show for it. Alerting on deliveryCount > 1 is a great cheap signal. The handler already gets it (in SmallRye it's on IncomingKafkaRecordMetadata, that's how my reproducer logs it).

To your question: in the 40s run with SmallRye's defaults it stalled before hitting the limit. The first record got handled 2 or 3 times depending on the run, then nothing, and the next record never showed up within 150s. I didn't check what the broker did with that first record afterwards, so I can't tell you if it ended up archived. In the scaled-down runs it did go all the way to 5 sometimes.

Good news though: a SmallRye maintainer confirmed it's a bug this morning and is working on a fix. I'll rerun it once that's out.

Collapse
 
ascendra_ventures_92c21f2 profile image
Ascendra Ventures •

The experiment table makes the lesson hard to miss: five deliveries and five side effects without deduplication, five deliveries and one side effect with it. The lock expiring is correct queue behaviour. The damage comes from a model call whose long tail nobody designed for.

Ascendra Ventures ran into the same tension on a candidate pipeline for a seed-stage talent platform, where enrichment depended on long OpenAI batch jobs and callbacks that sometimes went quiet. The requirement we settled on was that every candidate either finishes or visibly fails, and never gets stuck in the middle. The profile processor became a durable workflow: urgent profiles processed immediately, the rest batched, and fallback polling when a callback did not arrive. It reached 99.99% reliability at about $0.004 per candidate imported. The design question underneath was where state lives while a slow call is in flight, which is close to Sara's point about claiming the work before the model starts.

Have you tried keeping the claim outside Kafka entirely, keyed by the business id, and treating the share group only as delivery?

Collapse
 
mostavassoli profile image
Mostafa Tavassoli •

Thanks! "Finishes or visibly fails, never stuck in the middle" is a great way to put it.

No, I haven't tried that yet, all my tests keep the work under the Kafka lock. But for long calls it's probably where I'd end up. One thing I'd be careful about: save the claim first, then ack. Otherwise a failed write loses the event for good.

And then you own the stuff Kafka was doing for you, like retries and picking up work from a dead worker. Sounds like your fallback polling covers that part.

Collapse
 
sara_builds profile image
Sara •

The lock-renewal thread-safety catch is a nasty one. One thing I've started doing for slow model calls is claiming the work in the app before the LLM even starts: write a lease keyed by the event or business id with a TTL a bit longer than your p99, and only then call the model. A second delivery just sees the lease and skips, or waits and checks a result store. That cuts the duplicate token spend even when renewal or the framework fails, which your SmallRye case shows can happen. Idempotency on the side effect is still required, but the lease is what stops the five-times-the-cost problem.

Collapse
 
mostavassoli profile image
Mostafa Tavassoli •

Thanks Sara, that's a really good pattern, and it covers exactly the gap in the table: dedup on the side effect fixes the damage, a claim before the model call fixes the cost.

A few things I'd watch when combining it with share groups, based on what I saw in the tests:

  • The second delivery shouldn't ACCEPT just because it sees the lease. If the first worker dies after that, the record is gone for good. Releasing it, or waiting on the result store like you said, keeps it recoverable. But every release uses up one of the 5 deliveries, so the lease TTL and the delivery limit have to fit together.
  • A TTL a bit above p99 still leaves the tail: a call that runs past it lets a second worker start. Extending the lease while the call runs, or a fencing token on the side effect, closes that.
  • Taking the lease has to be atomic, e.g. a conditional insert or SET NX with an expiry.

In a way it moves lock renewal out of the framework and into your own code, which is the point: you control it and you can test it. I think it's worth adding as a fifth case to the test.