Search code examples
c#azureazure-functionssftpretry-logic

Sftp Retry Logic Inside Azure function App


I am facing one issue ,where i am getting intermittent error message

"An existing connection was forcibly closed by the remote host"

while trying to connect sftp server. I am trying to connect sftp inside azure function app. I believe this error happens while there is a connection issue.

To handle that I need to implement a retry logic incase if such error happens repeatedly connect sftp server with a specified delay until configured maximum retry count is reached. I believe the maximum execution time allowed for function app is 5 minutes (need to hear it from azure expert).

Can anyone help how i can achieve this retry functionality in C#?

I am using Renci.SshNet nuget package for managing sftp

using (var _sftpCn = new SftpClient(host, port, userName, password))
{
    _sftpCn.Connect();//error happens on this line:"An existing connection was forcibly closed by the remote host"
    log.LogInformation("Successful");
    byte[] byteArray = Encoding.UTF8.GetBytes(datacontent);
    sftpCl.WriteAllBytes("{remotePath}", byteArray);
    log.LogInformation("Sent successfully");
    _sftpCn.Disconnect();
}

Solution

  • I would suggest to use Polly here.

    Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and thread-safe manner.

    It is free library can be downloaded as nuget package from this command:

    dotnet add package Polly

    There are many more things to it, please see here and here for more details and examples.