AWS S3 .Net SDK - Help with Multipart Uploads. Getting tons of errors.

Hi Folks,

I’ve been wrangling with strange errors on uploading semi-large (5-20gb) zip files to my AWS bucket. Many parts upload ok, many parts throw an errror, get retried, and upload ok.. Many other parts fail all their retries. It’s seemingly random.

It seems I"m getting pretty much every error possible..Here are some of them:

  • No such host is known.
  • Error while copying content to a stream. Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
  • A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. I’ve increased the timeout to 2 hours, but this still happens, strangely enough
  • The SSL connection could not be established

Now, I’m doing the low-level api approach because the TransferUtility uploads timeout since they’re larger uploads. Here is the code I’m using. Any help and guidance is appreciated.

[edit] Reducing the initialthread count to 10, as illustrated in the code, seems to fix the issue. Initially I was using all available threads which caused the errors.

public static async Task UploadObjectAsync(string file, string bucketPath)
{
// Create list to store upload part responses.
List uploadResponses = new List();
FileInfo f = new FileInfo(file);
// Setup information required to initiate the multipart upload.
InitiateMultipartUploadRequest initiateRequest = new InitiateMultipartUploadRequest
{
BucketName = bucketPath,
Key = f.Name
};
// Initiate the upload.
InitiateMultipartUploadResponse initResponse =
await client.InitiateMultipartUploadAsync(initiateRequest);

        // Upload parts.
        long contentLength = new FileInfo(file).Length;            
        int totalParts = 0;
        long partSize = 32 * (long)Math.Pow(1024, 2); //8mb is the aws default
        List<UploadPartRequest> UPRs = new List<UploadPartRequest>();
        //begin the part uploading of a file
        Log.Info("Beginning Multipart Upload for: "+file);

long filePosition = 0;
//establish all the parts and the aws metadata stuff.
for (int i = 1; filePosition < contentLength; i++)
{
UploadPartRequest uploadRequest = new UploadPartRequest
{
BucketName = bucketPath,
Key = f.Name,
UploadId = initResponse.UploadId,
PartNumber = i,
PartSize = partSize,
FilePosition = filePosition,
FilePath = file
};

            /*
                * A WebException with status UnknownError was thrown.
                A connection attempt failed because the connected party did not properly respond after a period of time,
            or established connection failed because connected host has failed to respond.

often, when uploading large files, the aws connection times out for some reason. To override the timeout span,
we have to do this manual multipart upload scheme..

*/
uploadRequest.Timeout = new TimeSpan(2, 30, 0);
uploadRequest.ReadWriteTimeout = new TimeSpan(2, 30, 0);
UPRs.Add(uploadRequest);
totalParts++;
filePosition += partSize;
}
Log.Info("Total Parts: " + totalParts);

        ThreadPool.GetAvailableThreads(out int workerThreads, out int completionPortThreads);
        int partsDone = 0;
        var allTasks = new List<Task>();
        var throttler = new SemaphoreSlim(initialCount: 10); //perhaps less threads = less aws errors..
       
        foreach (UploadPartRequest upr in UPRs)
        {
            await throttler.WaitAsync();
            allTasks.Add(
                Task.Run(async () =>
                {
                    UploadPartResponse newUPR = new UploadPartResponse();
                    bool retry = true;
                    int tries = 1;
                    while (retry)
                    {
                        try
                        {
                            Console.WriteLine("Uploading Part: " + upr.PartNumber);
                            newUPR = await client.UploadPartAsync(upr);                                   
                            retry = false;
                            uploadResponses.Add(newUPR);
                        }
                        catch (Exception ex)
                        {
                            Log.Warning("Upload Exception on Part: " + upr.PartNumber + ". Upload Tries: "+tries);
                            Log.Info(ex.InnerException.Message);
                            if (tries !=5)
                                tries++;
                            else
                            {
                                retry = false;
                                Log.Error("Failed Uploading Part: "+upr.PartNumber);
                                throw;
                            }
                        }
                        finally
                        {
                            if(retry==false)
                                throttler.Release();                                    
                        }                                
                    }
                    partsDone++;
                    Console.WriteLine(f.Name + ": Part Done: " + upr.PartNumber.ToString() + " -- " + partsDone + "/" + totalParts);
                }));
        }
        await Task.WhenAll(allTasks);

Log.Info(“Completing Parts Upload”);
// Setup to complete the upload.
CompleteMultipartUploadRequest completeRequest = new CompleteMultipartUploadRequest
{
BucketName = bucketPath,
Key = f.Name,
UploadId = initResponse.UploadId
};
Log.Info(“Adding part e tags”);
completeRequest.AddPartETags(uploadResponses);
Log.Info(“Completing Upload”);
// Complete the upload.
CompleteMultipartUploadResponse completeUploadResponse =
await client.CompleteMultipartUploadAsync(completeRequest);
Log.Highlight("Parts Upload Complete for: " + file);
}
}

Haven’t read through the code, but in a multi part upload, you can only have a max of 10,000 pieces. Are you breaking your files up into more than 10,000 pieces?

I have a follow up question. Why native sdk breaks the file into chunks, and uses threading already. Any reason why you were reinventing the wheel?

I’ve tested below code by uploading 6GB file and it got successfully uploaded…

public static async Task UploadObjectAsync(string filePath, string bucketPath)

{

// Create an Amazon S3 client

AmazonS3Client s3Client = new AmazonS3Client(RegionEndpoint.USEast1);

try

{

var fileTransferUtility =

new TransferUtility(s3Client);

await fileTransferUtility.UploadAsync(filePath, bucketPath);

Console.WriteLine("Upload complete.");

}

catch (AmazonS3Exception e)

{

Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);

}

catch (Exception e)

{

Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);

}

}

The high level api breaks it up, yes, but there is a risk of upload timeout with large amount of parts which is what I’m encountering. It’s mentioned in the aws docs. That’s why I wrote this.

The high level api (TransferUtility) uploads, yes, but there is a risk of upload timeout with large amount of parts which is what I’m encountering. It’s mentioned in the aws docs. That’s why I wrote this.