This article is the second installment in a two-part series exploring retry and recovery strategies in Spring Kafka. In
the first part, we examined blocking and non-blocking retries, the architecture behind @RetryableTopic, backoff policies,
and topic reuse strategies. Building on those foundations, this second part explores scenarios where standard retry
mechanisms fall short, including custom retry routing, prolonged dependency outages, consumer pause/resume, circuit
breakers, and safe Dead Letter Topic (DLT) reprocessing. The focus shifts from simply retrying failed messages to designing
resilient systems that know when to retry, when to stop, and how to recover safely.
1. Not Every Failure Requires More Retries
Spring Kafka’s blocking and non-blocking retry mechanisms provide effective solutions for handling transient, message-specific failures.
However, assuming that every failure can be resolved by performing more retries is not always appropriate.
Consider the following scenarios:
- A downstream API remains unavailable for several hours.
- A database becomes completely inaccessible.
- A retry policy requires capabilities beyond standard backoff and topic reuse strategies.
- Messages cannot be processed because of business-state constraints rather than technical failures.
In these situations, the challenge is not simply retrying a message.
The real challenge is determining when to stop retrying, when to resume processing, and how to recover failed messages.
In this part, we will explore situations where Spring Kafka’s standard retry mechanisms may not be sufficient and examine alternative architectural approaches.
2. When Do We Need a Custom Retry Implementation?
Spring Kafka provides mechanisms that address a wide range of retry scenarios.
However, some requirements extend beyond the framework’s standard abstractions.
Reusing Intermediate Retry Topics
Consider the following retry policy:
5 × 2m
4 × 6h
2 × 12h
Suppose we want to execute these 11 retry attempts using only three physical retry topics.
retry-2m ↺ ↺ ↺ ↺
↓
retry-6h ↺ ↺ ↺
↓
retry-12h ↺
↓
DLT
Spring Kafka’s standard SINGLE_TOPIC strategy allows consecutive retry attempts with identical intervals to share a
topic only at the end of the retry chain.
Therefore, the topology above cannot be created using standard configuration.
Implementing this behavior requires an attempt-aware or stage-aware routing mechanism.
For example, each message could carry the following metadata:
retry-stage: 2
stage-attempt: 3
total-attempt: 8
The routing algorithm could then make decisions based on these values:
if (stageAttempt < stage.maxAttempts()) {
return currentRetryTopic;
}
return nextRetryTopic;
This code illustrates the concept; it is not Spring Kafka’s standard resolver implementation.
Although this approach is technically feasible with Kafka, developing custom routing also introduces additional responsibilities, including header management, attempt tracking, timeouts, DLT routing, and exception classification.
Dynamic Retry Policies
Retry delays may need to depend on message content or the state of an external system.
Examples include:
- A downstream service’s
Retry-Aftervalue - Transaction priority
- Scheduled maintenance windows
- Different retry strategies for different transaction types
Some requirements can be addressed through custom backoff policies. However, complex routing policies that change dynamically for individual messages at runtime may require custom routing or scheduling mechanisms.
Calendar-Based Retries
A transaction may need to be retried only on business days or at specific times.
In such cases, a persistent scheduler or workflow engine may be more appropriate than relative backoff intervals.
Preserving Processing Order
Non-blocking retries do not preserve the original processing order of messages.
If debit, refund, and reversal operations against the same wallet must be applied in a particular sequence, retry topics alone may not provide the required guarantees.
Business-State-Dependent Recovery
Some failures are related to business state rather than technical infrastructure.
For example, when a payment request times out, the appropriate action may be to query the payment provider for the current transaction status rather than immediately submitting the payment again.
In this situation, the problem is not merely retrying a request; it is managing a recovery workflow.
3. Controlling Message Processing During Prolonged Dependency Outages
Retry mechanisms in Kafka-based systems are generally designed to address transient, message-specific failures. However, prolonged unavailability of a database or downstream service introduces a different problem.
For example, if the database used by a payment service becomes completely inaccessible, retrying every incoming payment message may not be meaningful.
Messages may continue moving through retry topics, increasing system load and eventually reaching the DLT as their retry limits are exhausted.
payments
|
| Database unavailable
v
retry-2m
|
v
retry-6h
|
v
retry-12h
|
v
DLT
In this case, the problem is not caused by the individual messages. It originates from a shared dependency affecting all messages.
A more appropriate approach is to temporarily suspend message processing while ensuring that failed messages can be safely redelivered, then resume processing when the dependency becomes available again.
Spring Kafka provides acknowledgment, negative acknowledgment, and container pause/resume mechanisms that can help implement this behavior. Circuit breakers and independent health probes can automate the process.
3.1. Manual Acknowledgment and Negative Acknowledgment
Spring Kafka supports manual acknowledgment, allowing applications to control when message offsets are committed.
When AckMode.MANUAL or AckMode.MANUAL_IMMEDIATE is configured, the listener can use the Acknowledgment object to
indicate the processing outcome.
@KafkaListener(
id = "paymentListener",
topics = "payments",
containerFactory = "manualAckFactory"
)
public void consume(
PaymentEvent event,
Acknowledgment ack) {
paymentService.process(event);
ack.acknowledge();
}
In this example, acknowledge() is called after the message has been processed successfully.
However, an important distinction must be made:
Acknowledgment communicates the processing outcome to the offset commit mechanism; it does not directly control whether the consumer proceeds to the next message.
From the Kafka consumer’s perspective, two offset concepts are particularly important:
- Consumer position: The position from which the consumer will continue reading during the next
poll(). - Committed offset: The position from which the consumer group will resume after a restart or partition reassignment.
For example, a consumer may have polled records with offsets 100–103 from a partition. Its consumer position may therefore have advanced to 104.
Failing to acknowledge the record at offset 100 does not automatically reset the consumer position to 100.
Consequently, the following approach is unsafe:
try {
paymentService.process(event);
ack.acknowledge();
} catch (DependencyUnavailableException ex) {
log.error("Processing failed", ex);
// No acknowledgment
}
Because the exception is caught and the listener returns normally, Spring Kafka’s error handler is not invoked. The consumer may continue processing subsequent messages.
Furthermore, when subsequent messages are acknowledged, the failed message’s offset may also fall within the committed range under normal sequential acknowledgment behavior.
Therefore, simply omitting acknowledge() does not guarantee redelivery or prevent the consumer from progressing.
Negative Acknowledgment
Spring Kafka also supports nack(), which explicitly requests redelivery of a failed record.
@KafkaListener(
id = "paymentListener",
topics = "payments",
containerFactory = "manualAckFactory"
)
public void consume(
PaymentEvent event,
Acknowledgment ack) {
try {
paymentService.process(event);
ack.acknowledge();
} catch (DependencyUnavailableException ex) {
ack.nack(Duration.ofSeconds(30));
}
}
When nack() is called, Spring Kafka adjusts the consumer’s position so that the failed record can be redelivered.
The consumer also suspends message processing for the specified duration. Its polling loop continues, allowing consumer group membership to be maintained.
Unlike simply omitting acknowledge(), nack() explicitly requests redelivery.
However, several limitations must be considered:
nack()must be called on the consumer thread.- The effective delay is subject to the granularity determined by the consumer’s
pollTimeout. - The pause affects all partitions assigned to the consumer, not just the partition containing the failed record.
nack()cannot be used together withasyncAcks.- If the dependency remains unavailable when the delay expires, processing may fail again.
For example, if a database remains unavailable for two hours, using nack(Duration.ofSeconds(30)) may cause the same
message to be retried approximately every 30 seconds.
This may be acceptable for short, predictable interruptions. However, prolonged outages of unknown duration are better handled by explicitly managing the consumer lifecycle.
3.2. Container Pause/Resume
Spring Kafka listener containers support temporarily suspending and resuming message processing.
The pause() and resume() operations provide this capability.
MessageListenerContainer container =
registry.getListenerContainer("paymentListener");
container.pause();
Once the dependency becomes available again:
container.resume();
When a container is paused, the consumer continues polling, allowing it to maintain consumer group membership while suspending the delivery of new records to the listener.
The primary difference between this approach and nack() is that the pause is not limited to a predefined duration.
With nack(Duration), processing resumes after the specified delay. With pause(), the container can remain paused
until the application explicitly calls resume().
Dependency unavailable
|
v
Pause Kafka Listener
|
| Consumer polling continues
| Message processing suspended
|
v
Dependency recovered
|
v
Resume Kafka Listener
However, pausing a container does not automatically guarantee redelivery of the failed message.
If a listener encounters a database error while processing a message and the container is paused, the application must still determine how to handle the in-flight record.
Possible mechanisms include DefaultErrorHandler, negative acknowledgment, or another safe recovery strategy.
The important requirement is to prevent the failed record’s offset from being committed incorrectly and ensure that the record can be safely processed again after the consumer resumes.
Additionally, calling pause() does not immediately interrupt a message that is already being processed. The pause
request takes effect within the container’s polling lifecycle.
Another consideration is the scope of the pause operation.
Pausing only the main topic listener may not be sufficient. If retry topic listeners depend on the same unavailable database or downstream service, they may continue processing existing retry messages and eventually send them to the DLT.
Therefore, the pause/resume policy should consider all relevant main and retry listener containers.
Finally, continued polling does not automatically guarantee that Kubernetes readiness probes will remain successful. Readiness behavior depends on the application’s health indicators and readiness configuration.
3.3. Resilience4j Circuit Breaker
Resilience4j Circuit Breaker can be used to monitor downstream service calls and determine dependency availability based on failure rates and performance.
Suppose a payment service communicates with an external payment gateway through HTTP requests.
First, configure the circuit breaker:
resilience4j:
circuitbreaker:
instances:
paymentGateway:
slidingWindowType: COUNT_BASED
slidingWindowSize: 10
minimumNumberOfCalls: 5
failureRateThreshold: 50
waitDurationInOpenState: 30s
permittedNumberOfCallsInHalfOpenState: 3
automaticTransitionFromOpenToHalfOpenEnabled: true
recordExceptions:
- com.example.payment.PaymentGatewayUnavailableException
With this configuration, once at least five calls have been recorded, the circuit breaker may transition to OPEN if the
failure rate reaches or exceeds 50%.
After 30 seconds, it can transition to HALF_OPEN, allowing a limited number of test calls.
Protecting Payment Gateway Calls with a Circuit Breaker
The payment gateway client can execute its operations through the circuit breaker:
@Service
public class PaymentGatewayClient {
private final CircuitBreaker circuitBreaker;
private final PaymentGatewayApi api;
public PaymentGatewayClient(
CircuitBreakerRegistry registry,
PaymentGatewayApi api) {
this.circuitBreaker =
registry.circuitBreaker("paymentGateway");
this.api = api;
}
public void process(PaymentEvent event) {
circuitBreaker.executeRunnable(
() -> api.process(event)
);
}
}
Here, PaymentGatewayApi represents an application-specific client interface used to communicate with the external service.
The circuit breaker tracks configured exceptions raised during these calls and may transition to OPEN when the failure
threshold is exceeded.
Managing the Kafka Container Through Circuit Breaker Events
We can connect circuit breaker state transition events to the Kafka listener container.
@Component
public class PaymentCircuitBreakerCoordinator {
public PaymentCircuitBreakerCoordinator(
CircuitBreakerRegistry registry,
KafkaListenerEndpointRegistry kafkaRegistry) {
CircuitBreaker breaker =
registry.circuitBreaker("paymentGateway");
breaker.getEventPublisher()
.onStateTransition(event -> {
MessageListenerContainer container =
kafkaRegistry.getListenerContainer(
"paymentListener"
);
if (container == null) {
return;
}
switch (event.getStateTransition()) {
case CLOSED_TO_OPEN,
HALF_OPEN_TO_OPEN ->
container.pause();
case HALF_OPEN_TO_CLOSED ->
container.resume();
default -> { }
}
});
}
}
With this integration, the Kafka listener is paused when the circuit breaker transitions to OPEN.
The state transition callback is responsible only for lifecycle management. Safe redelivery of the failed Kafka message must be handled separately through the listener’s error-handling and redelivery policy.
The Recovery Problem in HALF_OPEN State
This approach introduces an important challenge.
When the circuit breaker is OPEN and the Kafka consumer is paused, the listener no longer makes calls to the downstream
service.
After transitioning to HALF_OPEN, the circuit breaker needs test calls to determine whether the dependency has recovered.
However, because the consumer remains paused, those calls may never occur.
As a result, the circuit breaker may never return to CLOSED, leaving the Kafka consumer paused indefinitely.
To solve this problem, an independent probe mechanism can execute test calls while the circuit breaker is in HALF_OPEN.
These probe calls should pass through the same circuit breaker so that their results contribute to state transitions.
@Component
public class PaymentGatewayRecoveryProbe {
private final CircuitBreaker breaker;
private final PaymentGatewayApi api;
public PaymentGatewayRecoveryProbe(
CircuitBreakerRegistry registry,
PaymentGatewayApi api) {
this.breaker =
registry.circuitBreaker("paymentGateway");
this.api = api;
}
@Scheduled(fixedDelay = 5000)
public void probe() {
if (breaker.getState()
!= CircuitBreaker.State.HALF_OPEN) {
return;
}
try {
breaker.executeRunnable(api::healthCheck);
} catch (Exception ignored) {
// Circuit breaker records the failure.
}
}
}
This example requires scheduling to be enabled through @EnableScheduling.
The healthCheck() operation should produce exceptions recognized by the circuit breaker and should meaningfully verify
that the dependency is available.
After the configured number of successful HALF_OPEN calls, the circuit breaker may transition to CLOSED. This
transition triggers the Kafka listener’s resume operation.
PaymentGateway failures
|
v
CircuitBreaker OPEN
|
v
Kafka Listener PAUSED
|
v
CircuitBreaker HALF_OPEN
|
v
Independent Recovery Probe
|
+--- Failed ---> OPEN
|
+--- Successful
|
v
CircuitBreaker CLOSED
|
v
Kafka Listener RESUMED
In this model, the circuit breaker manages both failure detection and recovery decisions.
However, transitioning to OPEN does not guarantee that the currently failing Kafka message will be safely redelivered.
The listener must propagate the exception to an appropriate error handler or use another explicit redelivery mechanism.
If multiple main and retry listeners depend on the same downstream service, all relevant containers should be managed together.
3.4. Health Probe Watchdog
When a circuit breaker is unnecessary, a simpler alternative is to implement a watchdog that detects dependency failures, pauses Kafka consumers, and independently monitors recovery.
This approach consists of three components:
- Kafka Listener: Detects dependency failures and triggers the watchdog.
- HealthProbeWatchdog: Pauses the listener container and starts periodic health checks.
- DependencyHealthProbe: Checks whether the dependency has become available again.
Dependency Health Probe
First, define a component responsible for checking dependency availability:
@Component
public class PaymentGatewayHealthProbe {
private final PaymentGatewayApi api;
public PaymentGatewayHealthProbe(
PaymentGatewayApi api) {
this.api = api;
}
public boolean isHealthy() {
try {
api.healthCheck();
return true;
} catch (Exception ex) {
return false;
}
}
}
The healthCheck() operation should have a short timeout and should ideally be free of side effects.
Implementing HealthProbeWatchdog
The watchdog uses KafkaListenerEndpointRegistry to manage the Kafka listener container and TaskScheduler to schedule
periodic health checks.
@Component
public class HealthProbeWatchdog {
private final KafkaListenerEndpointRegistry registry;
private final TaskScheduler scheduler;
private final PaymentGatewayHealthProbe healthProbe;
private final AtomicBoolean recovering =
new AtomicBoolean(false);
private volatile ScheduledFuture<?> recoveryTask;
public HealthProbeWatchdog(
KafkaListenerEndpointRegistry registry,
TaskScheduler scheduler,
PaymentGatewayHealthProbe healthProbe) {
this.registry = registry;
this.scheduler = scheduler;
this.healthProbe = healthProbe;
}
public void onDependencyUnavailable() {
if (!recovering.compareAndSet(false, true)) {
return;
}
MessageListenerContainer container =
registry.getListenerContainer("paymentListener");
if (container == null) {
recovering.set(false);
throw new IllegalStateException(
"Kafka listener not found"
);
}
container.pause();
recoveryTask = scheduler.scheduleAtFixedRate(
() -> checkRecovery(container),
Duration.ofSeconds(10)
);
}
private void checkRecovery(
MessageListenerContainer container) {
if (!healthProbe.isHealthy()) {
return;
}
container.resume();
ScheduledFuture<?> task = recoveryTask;
if (task != null) {
task.cancel(false);
}
recovering.set(false);
}
}
The AtomicBoolean prevents multiple recovery tasks from being started when several messages encounter dependency
failures concurrently.
This example is simplified for a single listener container and a single dependency.
In production, task creation, cancellation, and recovery state transitions require careful concurrency management. In
particular, the implementation should not assume that the recoveryTask reference has already been assigned before a
scheduled task can execute.
Triggering the Watchdog from the Kafka Listener
Next, integrate the watchdog into the Kafka listener:
@Component
public class PaymentEventListener {
private final PaymentService paymentService;
private final HealthProbeWatchdog watchdog;
public PaymentEventListener(
PaymentService paymentService,
HealthProbeWatchdog watchdog) {
this.paymentService = paymentService;
this.watchdog = watchdog;
}
@KafkaListener(
id = "paymentListener",
topics = "payments"
)
public void consume(PaymentEvent event) {
try {
paymentService.process(event);
} catch (PaymentGatewayUnavailableException ex) {
watchdog.onDependencyUnavailable();
throw ex;
}
}
}
When the listener encounters PaymentGatewayUnavailableException, it triggers the watchdog.
The watchdog pauses the corresponding listener container and starts a background health-check task.
The listener then rethrows the exception, delegating responsibility for the failed message to Spring Kafka’s error-handling mechanism.
An important distinction must be made here:
Rethrowing the exception and pausing the container do not, by themselves, guarantee that the message will remain on the original topic.
For example, if the listener uses @RetryableTopic, Spring Kafka may publish the failed message to a retry topic.
Therefore, pause/resume behavior must be designed together with the error handler and retry topology.
If the goal is to retain a failed message on the main topic during a prolonged dependency outage, DefaultErrorHandler
can be configured with an appropriate seek/retry policy.
However, the interaction between container pausing, blocking retry behavior, and subsequent redelivery must be carefully tested.
Recovery Flow
When the watchdog determines that the dependency is available again, it resumes the container.
Kafka Listener
|
v
PaymentGatewayUnavailableException
|
v
watchdog.onDependencyUnavailable()
|
+---- Pause Kafka Listener
|
+---- Schedule Health Probe
|
v
Health Check
|
+--------+--------+
| |
Unhealthy Healthy
| |
v v
Check Again Resume Listener
|
v
Cancel Probe Task
The main advantage of this approach over circuit breaker integration is that the recovery decision is completely independent of Kafka listener processing.
On the other hand, capabilities provided by circuit breakers, such as failure-rate tracking, slow-call detection, and state transition management, may need to be implemented separately if required.
3.5. Choosing the Right Approach
Manual acknowledgment, negative acknowledgment, container pause/resume, and circuit breakers are not direct substitutes for one another.
Each mechanism addresses a different responsibility.
| Mechanism | Primary responsibility | Typical use case |
|---|---|---|
| Manual Acknowledgment | Offset commit control | Acknowledging successful processing |
| Negative Acknowledgment | Redelivery of failed messages | Short-lived transient failures |
| DefaultErrorHandler | Retry and recovery management | Configured error-handling policies |
| Container Pause/Resume | Controlling message processing | Prolonged dependency outages |
| Circuit Breaker | Failure detection and call protection | Protecting downstream services |
| Health Probe Watchdog | Detecting dependency recovery | Automated recovery and resume |
For example, blocking retries or nack(Duration) may be sufficient for a connection problem expected to last only a few
seconds.
However, when a database becomes unavailable for an extended period, pausing the consumer may be preferable to repeatedly retrying the same message.
In such an architecture, responsibilities can be separated as follows:
Kafka Listener
|
v
Process Message
|
+---- Success
| |
| v
| Acknowledge
|
+---- Dependency Failure
|
v
Secure Redelivery
(ErrorHandler / Nack)
|
v
Pause Relevant Consumers
|
v
Recovery Watchdog
|
v
Dependency Healthy
|
v
Resume Consumers
This flow is conceptual. The actual implementation must account for the fact that nack() must execute on the consumer
thread, pause requests take effect within the polling lifecycle, and error handlers control recovery behavior.
Manual acknowledgment is not mandatory in every scenario. Safe retry and recovery flows can also be implemented using
DefaultErrorHandler with container-managed acknowledgment.
Ultimately, these mechanisms should be evaluated around three responsibilities:
Acknowledgment: When should a message be considered successfully processed?
Redelivery: How should a failed message be processed again?
Flow Control: When should processing of new messages resume?
Separating these responsibilities helps reduce unnecessary retry traffic while managing the risks of message loss and duplicate processing during prolonged dependency outages.
4. DLT Usage Principles
The Dead Letter Topic (DLT) is an important component of Kafka retry architectures.
However, it should not become a general-purpose waiting area where messages accumulate after every transient failure.
As a general architectural principle, the DLT should be treated as the terminal destination for messages whose retry attempts have been exhausted or that cannot be processed under the current conditions.
Typical examples include:
- Messages that have exhausted their retry attempts
- Poison-pill messages
- Messages rejected because of non-retryable exceptions
- Messages requiring manual or operational intervention
@DltHandler and Operational Recovery
Spring Kafka’s @DltHandler annotation allows applications to process messages that have reached the DLT.
The handler can create incident records, notify monitoring systems, or initiate workflows requiring manual intervention.
However, handling a message in the DLT and reintroducing it into the retry flow are two different responsibilities.
@DltHandler is primarily responsible for handling messages delivered to the DLT.
Re-drive, on the other hand, refers to deliberately republishing a message for processing again once specific conditions have been satisfied.
Therefore, automatically sending every DLT message back to the beginning of the retry chain from within the DLT handler is generally not a recommended approach.
The DLT Loop Anti-Pattern
Some systems redirect messages that reach the DLT back to the beginning of the retry topic hierarchy.
main
↓
retry-2m
↓
retry-6h
↓
DLT
|
+--------→ retry-2m
Without careful design, this approach can create an infinite retry loop.
Particularly during shared dependency outages, continuously redirecting DLT messages into retry topics creates repeated load rather than resolving the underlying problem.
Therefore, DLT looping should not be treated as a general-purpose retry strategy.
5. Designing a Safe DLT Re-Drive Mechanism
After operational intervention, it may become necessary to reprocess messages stored in the DLT.
For example:
- An application bug has been fixed.
- Missing reference data has been restored.
- A downstream service has become available again.
- A transaction has received the required manual correction.
In these cases, a controlled re-drive or re-publisher mechanism can be used.
Such a mechanism should address several important responsibilities.
Header and Metadata Management
When a message is reintroduced into the retry flow, the system must determine how to handle existing retry attempt counters, retry timestamps, exception metadata, and destination information.
Spring Kafka uses specific headers for retry routing and attempt management. Preserving or modifying these headers without a clear policy may lead to unexpected behavior.
The original message identity and business correlation information should be preserved, while metadata associated with the new retry lifecycle must remain consistent.
Global Retry Limits
The system should track how many times a message has been reprocessed from the DLT.
Applying attempt limits only within each individual retry chain is insufficient. Otherwise, every re-drive operation could grant the message a new set of retry attempts, potentially allowing it to circulate indefinitely.
Global retry or re-drive limits should therefore be enforced.
Rate Limiting and Throttling
Reintroducing thousands of accumulated DLT messages simultaneously can generate substantial load.
For example:
DLT: 100,000 messages
|
| Bulk re-drive
v
retry-2m
|
| 2 minutes later
v
Downstream API overload
This can lead to a thundering herd problem.
A thundering herd occurs when a large number of waiting operations become active simultaneously and attempt to access the same shared resource.
A re-drive mechanism should therefore support controlled batch sizes, rate limiting, throttling, and, when appropriate, jitter.
Poison-Pill Detection
Not every DLT message should be automatically reprocessed.
For example, a message rejected because of a permanent validation error will likely fail again if it is reintroduced without correcting the underlying problem.
Therefore, the failure reason and eligibility for reprocessing should be evaluated before initiating re-drive.
Observability and Auditability
Re-drive operations should be traceable.
The system should record which messages were reprocessed, why they were selected, who or what initiated the operation, and whether reprocessing succeeded.
DLT re-drive should be treated as a controlled recovery operation rather than just another retry attempt.
6. Key Considerations in Retry Architecture
Regardless of how sophisticated a retry mechanism becomes, it does not eliminate several fundamental distributed-systems challenges.
Idempotency
The same message may be processed more than once.
Especially in payment and wallet systems, retry mechanisms must be designed together with idempotent processing.
Ordering
Non-blocking retries do not preserve the original processing order of messages.
Retry Storms
When an external service becomes available again, a large number of retries may be triggered simultaneously.
Backoff, jitter, concurrency, and rate limiting should be considered together.
Retention
For long-running retry policies, Kafka topic retention periods must be long enough to accommodate the expected retry horizon and potential operational delays.
Observability
Monitoring consumer lag on retry topics alone is insufficient.
Important metrics also include retry attempt distributions, retry age, DLT volume, exception categories, and recovery success rates.
Poison Messages
Not every error should be retried.
For deserialization failures, validation errors, or permanent business-rule violations, routing messages directly to the DLT or a separate error-handling workflow may be more appropriate than exhausting retry attempts.
Transaction Boundaries
Spring Kafka’s non-blocking retry mechanism is not supported with container transactions.
Retry strategies must therefore be evaluated separately for transactional consumer designs.
7. Conclusion
In summary, Spring Kafka’s blocking and non-blocking retry mechanisms address a wide range of transient failure scenarios.
However, not every failure should be resolved by performing more retries.
For prolonged dependency outages, consumer pause/resume may be more appropriate. For permanently unprocessable messages, the DLT provides a terminal destination. Following operational corrections, controlled re-drive mechanisms can enable safe recovery.
Especially in payment systems, retry architecture must be designed together with idempotency, ordering, transaction boundaries, dependency availability, and recovery workflows.
A well-designed retry architecture is not about retrying every failed operation. It is about retrying the right operation, at the right time, under the right conditions.