AI calls are slow, costly and sometimes fail. Learn how to run them asynchronously with Spring Boot and Kafka using request and result topics, idempotency, retries and dead-letter topics.
Adding an AI feature to a business application often starts with a simple synchronous call: the user clicks a button, the server calls a language model or a document-processing API, and the response comes back. That works in a demo. In production, it runs into trouble. Model calls can take several seconds, providers apply rate limits, requests occasionally time out, and every retry costs money. If hundreds of users trigger the feature at once, web server threads pile up waiting, and the whole application slows down.
An event-driven design separates "asking for the AI work" from "doing the AI work". The application publishes a request as an event, a pool of workers processes requests at a controlled pace, and results are published back. Apache Kafka and Spring Boot, through the spring-kafka library, are a common combination for this in Java teams. This article covers the design decisions that make such a system reliable.
Why asynchronous processing suits AI workloads
AI tasks have characteristics that fit asynchronous processing well:
- Variable latency. A short prompt may return quickly; a long document may take much longer. Users should not hold an open HTTP request for that.
- External limits. Providers limit requests and tokens per minute. A queue lets you stay within those limits instead of failing under bursts.
- Batch-friendly work. Summarising yesterday's support tickets or classifying a catalogue of products does not need an instant answer.
- Independent scaling. AI workers can be scaled up or down separately from the web tier, and even deployed on different hardware.
The user experience changes slightly: the user submits a request, sees a "processing" state, and gets the result through polling, a WebSocket update or a notification. For many business features, such as invoice data extraction or a report summary, this is entirely acceptable.
Designing request and result topics
A clear topic layout keeps the system understandable. A typical design uses:
ai.summary.requests: events containing a request ID, the input (or a reference to it) and metadata such as tenant and requested time.ai.summary.results: events containing the request ID, the output, status and the model used.- Retry and dead-letter topics, discussed below.
Some guidelines:
- Use a stable key. Keying messages by request ID or customer ID controls partitioning, and Kafka preserves order only within a partition.
- Send references for large inputs. Put a PDF in object storage and send its location, rather than putting megabytes into a Kafka message.
- Version your event schema. Add a version field or use a schema registry so producers and consumers can evolve independently.
- Mind personal data. Kafka retains messages for a configured period. If events contain personal data, the retention and access settings need to reflect your obligations under the DPDP Act, 2023.
Idempotency: processing each request once in effect
Kafka consumers in typical configurations give at-least-once delivery. If a worker crashes after calling the model but before committing its offset, the message will be delivered again. For AI work, duplicate processing means duplicate cost and possibly duplicate results sent to users.
The answer is to make the consumer idempotent. Each request carries a unique ID. Before doing expensive work, the worker checks whether that ID has already been processed, typically in a database table with a unique constraint. Downstream consumers of the results topic should also tolerate duplicates, for example by upserting results by request ID rather than inserting blindly.
A spring-kafka listener with retries and a dead-letter topic
spring-kafka provides @KafkaListener for consuming messages and @RetryableTopic for non-blocking retries. With @RetryableTopic, a failed message is moved to a retry topic and attempted again after a delay, so it does not block other messages in the partition. After the final attempt fails, it goes to a dead-letter topic, which a @DltHandler method can handle. (Constructor injection is omitted below for brevity; JSON serialisation is configured in application properties.)
@Component
public class SummaryRequestListener {
// SummaryService, ProcessedRequestRepository and KafkaTemplate injected via constructor
@RetryableTopic(attempts = "4", backoff = @Backoff(delay = 2000, multiplier = 2.0))
@KafkaListener(topics = "ai.summary.requests", groupId = "summary-workers")
public void onRequest(SummaryRequest request) {
if (processedRepository.existsById(request.requestId())) {
return; // already handled: skip duplicate delivery
}
String summary = summaryService.summarise(request.text());
kafkaTemplate.send("ai.summary.results", request.requestId(),
new SummaryResult(request.requestId(), "DONE", summary));
processedRepository.save(new ProcessedRequest(request.requestId()));
}
@DltHandler
public void onDeadLetter(SummaryRequest request) {
kafkaTemplate.send("ai.summary.results", request.requestId(),
new SummaryResult(request.requestId(), "FAILED", null));
}
}
Two refinements are worth adding in a real system. First, not every error deserves a retry: invalid input will fail every time, so configure such exceptions as non-retryable and send them straight to the dead-letter topic. Second, the dead-letter handler should record enough context (error type, attempt count, timestamps) for someone to investigate and, if appropriate, replay the message after a fix. Check the spring-kafka reference documentation for the version you use, as options and defaults change between releases.
Back-pressure: protecting the model provider and yourself
A queue absorbs bursts, but workers still need to process at a rate the AI provider accepts. Kafka's pull-based model helps here: consumers fetch messages when they are ready, so a slow worker does not get flooded. Useful controls include:
- Consumer concurrency. The
concurrencysetting on the listener container controls how many consumer threads run. Parallelism within one consumer group is capped by the number of partitions. - Batch size.
max.poll.recordslimits how many messages a poll returns. - Poll interval.
max.poll.interval.msmust be longer than the time it takes to process a batch, or the consumer will be considered dead and its partitions reassigned, causing duplicate processing. - Client-side rate limiting. A rate limiter around the model call (Resilience4j has one) keeps you under provider quotas even when you scale workers.
- Lag monitoring. Consumer lag, the gap between the newest message and the last processed one, tells you whether workers are keeping up. Alert when it grows steadily.
Operating the system
Event-driven systems are harder to observe than a single request-response call, so plan for visibility from the start. Propagate a correlation ID from the original HTTP request through every event and log line. Track per-request latency from submission to result, model errors by type, dead-letter counts and spending on AI calls per day. Test failure paths deliberately: stop the model provider in a staging environment and confirm that retries, dead-letter handling and user notifications behave as intended.
How NextWebGen can help
NextWebGen designs and builds back-end systems, including Spring Boot services and the servers and infrastructure they run on. If you plan to add AI processing to an existing application and want it to stay responsive and dependable under real load, we can help design the event flow, implement the workers and set up monitoring. Request a free quote to talk through your requirements.



