Implementing Retry Logic with Backoff and Cancellation in C# Asynchronous Tasks

I have a service which runs as a background job. It’s duty is to try and hit some external service for some external update. Now, I am to attempt retrying an HTTP request against the service for a specified number of times. Ultimately, after the third try, I am to backoff for a few minutes, and try one more time. The service should return on failure of the fourth try.

My service roughly looks like this:

 var cts = new CancellationTokenSource();
                var cancellationToken = cts.Token;
                //create a task responsible for syncing data
                Func<Task<RequestResponse<SomeResponse>>>> task = async () =>
                {
                    var url = $"https://google.com/v1/abcdefhj";
                    var response = await _requestService.Post<SomeResponse>>(
                                       url,
                                       customerProfile,
                                       nameof(SomeOperation),
                                       _auth,
                                       "Bearer"
                                   );
                    return new RequestResponse<SomeResponse>
                    {
                        Data = response.Data,
                        Successful = response.Successful,
                        Message = response.Message
                    };
                };
                
                var response = await AttemptUpdate(task, cancellationToken, _options.Value.MaxRetries);
              
                if (!response.Successful)
                {
                    _logger.LogDebug("Setting backoff time for {BackoffTime} minutes", _options.Value.BackoffTime);
                    //set the backoff time here
                    await Task.Delay(TimeSpan.FromMinutes(_options.Value.BackoffTime), cancellationToken);
                    
                    var url = $"https://google.com/v1/abcdefghij";
                    var responseFromRetry = await _requestService.Post<SomeResponse>>(
                                       url,
                                       customerProfile,
                                       nameof(SomeAction),
                                       _auth,
                                       "Bearer"
                                   );
                    _logger.LogDebug("Response from retry --> {Response}",
                        JsonConvert.SerializeObject(responseFromRetry));
                    response =  new RequestResponse<SomeResponse>>
                    {
                        Data = responseFromRetry.Data,
                        Successful = responseFromRetry.Successful,
                        Message = responseFromRetry.Message
                    };

                    if (!response.Successful)
                    {
                        _logger.LogDebug("Failed to sync profile after 3 attempts. Skipping.");
                        break;
                    }
                }

For some weird reason, my service never hits _logger.LogDebug("Response from retry --> {Response}", although the condition for failure is true.

This is how my retry function is:

private async Task<RequestResponse<SomeResponse>> AttemptUpdate(
            Func<Task<RequestResponse<SomeResponse>>>> task, CancellationToken cancellationToken,
            int maxAttemptCount = 3)
        {
            for (var attempted = 0; attempted < maxAttemptCount; attempted++)
            {
                _logger.LogDebug("Attempt {Attempted} to sync customer profile with Star Assurance", attempted + 1);
                
                // Check for cancellation
                if (cancellationToken.IsCancellationRequested)
                {
                    _logger.LogDebug("Cancellation requested. Exiting retry loop.");
                    return new RequestResponse<SomeResponse>>
                    {
                        Successful = false,
                        Message = "Operation cancelled"
                    };
                }
                var result = await task();
                _logger.LogDebug("Received response --> {Response}",
                     JsonConvert.SerializeObject(result));
                
                // Result is successful so we can return
                if (result.Successful)
                {
                    _logger.LogDebug("Succeeded to sync customer profile with response --> {Response}",
                        result.Data?.Message);
                    return result;
                }
                
                _logger.LogDebug("Failed to sync customer profile with response --> {Response}",
                    result.Data?.Message);
            }
            
            return new RequestResponse<SomeResponse>>
            {
                Successful = false,
                Message = "Failed to sync customer profile"
            };
        }

I have a feeling the introduction of asynchronicity is causing something I cannot detect. Or am I managing the threads wrongly? My desired goal is to return when the attempt post backoff fails. My backoff of 10 minutes does not run, but what happens is the list is iterated over again and enters AttemptUpdate again.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật