-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Add Spring Cloud Stream retry support to ServiceBus Binder #47149
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
19d7e38
Initial plan
Copilot f2c1549
Add Spring Cloud Stream retry support for ServiceBus Binder
Copilot 1a9398d
Add documentation for ServiceBus Binder retry configuration
Copilot 01e3bc4
Fix code style: remove extra blank line in setInstrumentationId
Copilot 9722515
Fix code style: replace double-brace initialization with explicit map…
Copilot 432cef9
Add support for custom RetryTemplate injection
Copilot 43a0e1c
Merge branch 'main' into copilot/fix-servicebus-backoff-settings
rujche 7af864f
Address PR feedback: remove retry doc file, fix changelog style, and …
Copilot f0be1c0
Fix changelog entry format in sdk/spring/CHANGELOG.md
Copilot fa45a5b
Merge branch 'main' into copilot/fix-servicebus-backoff-settings
rujche 463e525
Fix changelog headers and add retry execution test
Copilot 11d8ca6
Address trailing whitespace and derive retry defaults from ExtendedCo…
Copilot 2dc51cb
Fix CHANGELOG.md structure: remove empty top-level Features Added sec…
Copilot 1bf2489
Fix race condition and wire RetryTemplate from Spring context
Copilot e418dde
Add spring-retry direct dependency to binder pom and wire test
Copilot 5c5f7d0
Fix MockitoAnnotations resource leak: switch to @ExtendWith(MockitoEx…
Copilot 4207261
Simplify shouldConfigureRetry, fix retry+errorChannel, update tests
Copilot 6822a4e
Fix sendMessageDirectly false-return and shouldConfigureRetry semantics
Copilot 7f65c45
Fix misleading retry comment in ServiceBusMessageChannelBinder
Copilot 8961d7d
Replace Spring Retry reflection with public API and behavioral testing
Copilot 332f819
Replace ReflectionTestUtils with public getter for retryTemplate asse…
Copilot fae6b68
Address review: sendTimeout semantics, backoff reflection, exhausted-…
Copilot a123343
Clean up sendMessageDirectly, isolate binder per test, close context …
Copilot 6700e45
Fix unused import and qualify RetryTemplate injection to avoid ambiguity
Copilot 80c2c75
Merge origin/main into copilot/fix-servicebus-backoff-settings
Copilot af105d7
Merge origin/main: resolve CHANGELOG conflict, keep retry feature ent…
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
163 changes: 163 additions & 0 deletions
163
sdk/spring/spring-cloud-azure-stream-binder-servicebus/RETRY_CONFIGURATION.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| # ServiceBus Binder Retry Configuration | ||
|
rujche marked this conversation as resolved.
Outdated
|
||
|
|
||
| ## Overview | ||
|
|
||
| The ServiceBus Binder now supports Spring Cloud Stream's consumer retry properties, enabling automatic retry with exponential backoff for message processing failures. | ||
|
|
||
| ## Configuration | ||
|
|
||
| You can configure retry behavior using the following properties in your `application.yml` or `application.properties`: | ||
|
|
||
| ### YAML Configuration Example | ||
|
|
||
| ```yaml | ||
| spring: | ||
| cloud: | ||
| stream: | ||
| bindings: | ||
| consumer-in-0: | ||
| destination: my-queue | ||
| group: my-group | ||
| consumer: | ||
| max-attempts: 5 # Maximum number of retry attempts (default: 3) | ||
| back-off-initial-interval: 1000 # Initial backoff interval in milliseconds (default: 1000) | ||
| back-off-max-interval: 10000 # Maximum backoff interval in milliseconds (default: 10000) | ||
| back-off-multiplier: 2.0 # Backoff multiplier (default: 2.0) | ||
| binders: | ||
| servicebus: | ||
| type: servicebus | ||
| ``` | ||
|
|
||
| ### Properties Configuration Example | ||
|
|
||
| ```properties | ||
| spring.cloud.stream.bindings.consumer-in-0.destination=my-queue | ||
| spring.cloud.stream.bindings.consumer-in-0.group=my-group | ||
| spring.cloud.stream.bindings.consumer-in-0.consumer.max-attempts=5 | ||
| spring.cloud.stream.bindings.consumer-in-0.consumer.back-off-initial-interval=1000 | ||
| spring.cloud.stream.bindings.consumer-in-0.consumer.back-off-max-interval=10000 | ||
| spring.cloud.stream.bindings.consumer-in-0.consumer.back-off-multiplier=2.0 | ||
| ``` | ||
|
|
||
| ## How It Works | ||
|
|
||
| ### Retry Behavior | ||
|
|
||
| When a message processing fails (throws an exception), the binder will: | ||
|
|
||
| 1. **Retry Automatically**: Retry processing the message based on the `max-attempts` setting | ||
| 2. **Exponential Backoff**: Wait between retries using an exponential backoff strategy: | ||
| - First retry: waits `back-off-initial-interval` milliseconds | ||
| - Subsequent retries: wait time is multiplied by `back-off-multiplier` | ||
| - Maximum wait: capped at `back-off-max-interval` milliseconds | ||
|
|
||
| ### Example Retry Timeline | ||
|
|
||
| With the configuration above (`max-attempts: 5`, `back-off-initial-interval: 1000`, `back-off-multiplier: 2.0`, `back-off-max-interval: 10000`): | ||
|
|
||
| - **Attempt 1**: Initial processing (fails) | ||
| - **Wait**: 1000ms (1 second) | ||
| - **Attempt 2**: Retry 1 (fails) | ||
| - **Wait**: 2000ms (2 seconds) = 1000ms × 2.0 | ||
| - **Attempt 3**: Retry 2 (fails) | ||
| - **Wait**: 4000ms (4 seconds) = 2000ms × 2.0 | ||
| - **Attempt 4**: Retry 3 (fails) | ||
| - **Wait**: 8000ms (8 seconds) = 4000ms × 2.0 | ||
| - **Attempt 5**: Retry 4 (final attempt, fails) | ||
| - **Result**: Message is sent to error channel or dead letter queue (if configured) | ||
|
|
||
| ### After All Retries Exhausted | ||
|
|
||
| When all retry attempts are exhausted: | ||
|
|
||
| - If `requeue-rejected: false` (default), the message is **abandoned** | ||
| - If `requeue-rejected: true`, the message is sent to the **dead letter queue** | ||
|
|
||
| ## Consumer Example | ||
|
|
||
| ```java | ||
| @Bean | ||
| public Consumer<Message<String>> consumer() { | ||
| return message -> { | ||
| // This method will be automatically retried if it throws an exception | ||
| processMessage(message.getPayload()); | ||
| }; | ||
| } | ||
|
|
||
| private void processMessage(String payload) { | ||
| // Your business logic here | ||
| // If this throws an exception, the message will be retried | ||
| if (shouldFail(payload)) { | ||
| throw new RuntimeException("Processing failed"); | ||
| } | ||
| // Successfully processed | ||
| } | ||
| ``` | ||
|
|
||
| ## Dead Letter Queue Configuration | ||
|
|
||
| To send failed messages to the dead letter queue after all retries are exhausted: | ||
|
|
||
| ```yaml | ||
| spring: | ||
| cloud: | ||
| stream: | ||
| servicebus: | ||
| bindings: | ||
| consumer-in-0: | ||
| consumer: | ||
| requeue-rejected: true # Send failed messages to DLQ | ||
| ``` | ||
|
|
||
| ## Disabling Retry | ||
|
|
||
| To disable retry (process message only once), set `max-attempts` to 1: | ||
|
|
||
| ```yaml | ||
| spring: | ||
| cloud: | ||
| stream: | ||
| bindings: | ||
| consumer-in-0: | ||
| consumer: | ||
| max-attempts: 1 # No retries | ||
| ``` | ||
|
|
||
| ## Best Practices | ||
|
|
||
| 1. **Choose Appropriate Max Attempts**: Consider the nature of your failures. Transient network issues might benefit from more retries, while business logic errors might not. | ||
|
|
||
| 2. **Configure Realistic Backoff Intervals**: Ensure your backoff intervals are appropriate for your use case: | ||
| - Too short: May overwhelm downstream services | ||
| - Too long: May delay message processing unnecessarily | ||
|
|
||
| 3. **Monitor Dead Letter Queues**: Set up monitoring and alerting for messages in the DLQ to handle persistent failures. | ||
|
|
||
| 4. **Use Specific Exception Types**: Consider catching specific exceptions in your consumer and only retrying for transient errors. | ||
|
|
||
| 5. **Test Your Configuration**: Use integration tests to verify your retry configuration works as expected. | ||
|
|
||
| ## Troubleshooting | ||
|
|
||
| ### Retries Not Working | ||
|
|
||
| - Verify `max-attempts` is greater than 1 | ||
| - Check that exceptions are being thrown from your consumer | ||
| - Enable debug logging: `logging.level.org.springframework.retry=DEBUG` | ||
|
|
||
| ### Too Many Retries | ||
|
|
||
| - Reduce `max-attempts` | ||
| - Increase `back-off-initial-interval` or reduce `back-off-multiplier` | ||
| - Consider implementing circuit breaker patterns for persistent failures | ||
|
|
||
| ### Messages Going to DLQ Immediately | ||
|
|
||
| - Verify `requeue-rejected` is set correctly | ||
| - Check if `max-attempts` is set to 1 | ||
| - Review error handling logic in your consumer | ||
|
|
||
| ## Related Configuration | ||
|
|
||
| - [Spring Cloud Stream Binding Properties](https://docs.spring.io/spring-cloud-stream/docs/current/reference/html/spring-cloud-stream.html#_consumer_properties) | ||
| - [Azure Service Bus Error Handling](https://learn.microsoft.com/azure/service-bus-messaging/service-bus-dead-letter-queues) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
134 changes: 134 additions & 0 deletions
134
...a/com/azure/spring/cloud/stream/binder/servicebus/implementation/ServiceBusRetryTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,134 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
| package com.azure.spring.cloud.stream.binder.servicebus.implementation; | ||
|
|
||
| import com.azure.spring.cloud.service.servicebus.properties.ServiceBusEntityType; | ||
| import com.azure.spring.cloud.stream.binder.servicebus.core.implementation.provisioning.ServiceBusChannelProvisioner; | ||
| import com.azure.spring.cloud.stream.binder.servicebus.core.properties.ServiceBusBindingProperties; | ||
| import com.azure.spring.cloud.stream.binder.servicebus.core.properties.ServiceBusConsumerProperties; | ||
| import com.azure.spring.cloud.stream.binder.servicebus.core.properties.ServiceBusExtendedBindingProperties; | ||
| import com.azure.spring.integration.servicebus.inbound.ServiceBusInboundChannelAdapter; | ||
| import org.junit.jupiter.api.BeforeEach; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.mockito.Mock; | ||
| import org.mockito.MockitoAnnotations; | ||
| import org.springframework.cloud.stream.binder.BinderHeaders; | ||
| import org.springframework.cloud.stream.binder.ExtendedConsumerProperties; | ||
| import org.springframework.cloud.stream.binder.HeaderMode; | ||
| import org.springframework.cloud.stream.provisioning.ConsumerDestination; | ||
| import org.springframework.context.support.GenericApplicationContext; | ||
| import org.springframework.integration.core.MessageProducer; | ||
| import org.springframework.retry.support.RetryTemplate; | ||
| import org.springframework.test.util.ReflectionTestUtils; | ||
|
|
||
| import java.time.Duration; | ||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
| import static org.mockito.Mockito.when; | ||
|
|
||
| /** | ||
| * Tests for retry functionality in ServiceBusMessageChannelBinder. | ||
| */ | ||
| class ServiceBusRetryTest { | ||
|
|
||
| @Mock | ||
| private ConsumerDestination consumerDestination; | ||
|
|
||
| private final ServiceBusExtendedBindingProperties extendedBindingProperties = | ||
| new ServiceBusExtendedBindingProperties(); | ||
|
|
||
| private ExtendedConsumerProperties<ServiceBusConsumerProperties> consumerProperties; | ||
|
|
||
| private final ServiceBusConsumerProperties serviceBusConsumerProperties = new ServiceBusConsumerProperties(); | ||
|
|
||
| private final ServiceBusMessageChannelTestBinder binder = new ServiceBusMessageChannelTestBinder( | ||
| BinderHeaders.STANDARD_HEADERS, new ServiceBusChannelProvisioner()); | ||
|
|
||
|
rujche marked this conversation as resolved.
Outdated
|
||
| private static final String ENTITY_NAME = "test-entity"; | ||
| private static final String GROUP = "test"; | ||
| private static final String NAMESPACE_NAME = "test-namespace"; | ||
|
|
||
| @BeforeEach | ||
| void init() { | ||
| MockitoAnnotations.openMocks(this); | ||
| GenericApplicationContext context = new GenericApplicationContext(); | ||
| binder.setApplicationContext(context); | ||
| } | ||
|
rujche marked this conversation as resolved.
rujche marked this conversation as resolved.
|
||
|
|
||
| @Test | ||
| void testRetryTemplateConfiguredWhenMaxAttemptsGreaterThanOne() { | ||
| // Arrange | ||
| prepareConsumerProperties(); | ||
| consumerProperties.setMaxAttempts(3); | ||
| consumerProperties.setBackOffInitialInterval(1000); | ||
| consumerProperties.setBackOffMultiplier(2.0); | ||
| consumerProperties.setBackOffMaxInterval(5000); | ||
| when(consumerDestination.getName()).thenReturn(ENTITY_NAME); | ||
|
|
||
| // Act | ||
| MessageProducer producer = binder.createConsumerEndpoint(consumerDestination, GROUP, consumerProperties); | ||
|
|
||
| // Assert | ||
| assertThat(producer).isInstanceOf(ServiceBusInboundChannelAdapter.class); | ||
| ServiceBusInboundChannelAdapter adapter = (ServiceBusInboundChannelAdapter) producer; | ||
| RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(adapter, "retryTemplate"); | ||
| assertThat(retryTemplate).isNotNull(); | ||
| } | ||
|
rujche marked this conversation as resolved.
|
||
|
|
||
| @Test | ||
| void testRetryTemplateNotConfiguredWhenMaxAttemptsIsOne() { | ||
| // Arrange | ||
| prepareConsumerProperties(); | ||
| consumerProperties.setMaxAttempts(1); | ||
| when(consumerDestination.getName()).thenReturn(ENTITY_NAME); | ||
|
|
||
| // Act | ||
| MessageProducer producer = binder.createConsumerEndpoint(consumerDestination, GROUP, consumerProperties); | ||
|
|
||
| // Assert | ||
| assertThat(producer).isInstanceOf(ServiceBusInboundChannelAdapter.class); | ||
| ServiceBusInboundChannelAdapter adapter = (ServiceBusInboundChannelAdapter) producer; | ||
| RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(adapter, "retryTemplate"); | ||
| assertThat(retryTemplate).isNull(); | ||
| } | ||
|
|
||
| @Test | ||
| void testRetryTemplateNotConfiguredWhenMaxAttemptsNotSet() { | ||
| // Arrange | ||
| prepareConsumerProperties(); | ||
| // maxAttempts defaults to 3 in ExtendedConsumerProperties, | ||
| // but we test the case where it's explicitly set to 1 or not configured with retry | ||
| consumerProperties.setMaxAttempts(1); | ||
| when(consumerDestination.getName()).thenReturn(ENTITY_NAME); | ||
|
|
||
| // Act | ||
| MessageProducer producer = binder.createConsumerEndpoint(consumerDestination, GROUP, consumerProperties); | ||
|
|
||
| // Assert | ||
| assertThat(producer).isInstanceOf(ServiceBusInboundChannelAdapter.class); | ||
| ServiceBusInboundChannelAdapter adapter = (ServiceBusInboundChannelAdapter) producer; | ||
| RetryTemplate retryTemplate = (RetryTemplate) ReflectionTestUtils.getField(adapter, "retryTemplate"); | ||
| assertThat(retryTemplate).isNull(); | ||
| } | ||
|
rujche marked this conversation as resolved.
|
||
|
|
||
| private void prepareConsumerProperties() { | ||
| serviceBusConsumerProperties.setEntityName(ENTITY_NAME); | ||
| serviceBusConsumerProperties.setSubscriptionName(GROUP); | ||
| serviceBusConsumerProperties.setEntityType(ServiceBusEntityType.TOPIC); | ||
| serviceBusConsumerProperties.setNamespace(NAMESPACE_NAME); | ||
| serviceBusConsumerProperties.getRetry().setTryTimeout(Duration.ofMinutes(5)); | ||
| serviceBusConsumerProperties.setAutoComplete(false); | ||
| ServiceBusBindingProperties bindingProperties = new ServiceBusBindingProperties(); | ||
| bindingProperties.setConsumer(serviceBusConsumerProperties); | ||
|
|
||
| Map<String, ServiceBusBindingProperties> bindings = new HashMap<>(); | ||
| bindings.put(ENTITY_NAME, bindingProperties); | ||
| extendedBindingProperties.setBindings(bindings); | ||
| binder.setBindingProperties(extendedBindingProperties); | ||
|
|
||
| consumerProperties = new ExtendedConsumerProperties<>(serviceBusConsumerProperties); | ||
| consumerProperties.setHeaderMode(HeaderMode.embeddedHeaders); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.