Providing multipart upload code with parallel threading
Delivering a complete Python script using boto3 client to manually multipart upload large files over 100MB in parallel with ThreadPoolExecutor, including chunking logic, part numbering, and multipart completion steps with notes on chunk size, concurrency, and AWS config.
Below is an example Python script that uses boto3 to perform a manual multipart upload to S3 for files larger than 100 MB. It splits the file into chunks, uploads them in parallel threads, and finally calls CompleteMultipartUpload to assemble them on S3.
import os
import math
import boto3
from concurrent.futures import ThreadPoolExecutor, as_completed
def multipart_upload(
file_path,
bucket_name,
object_key,
chunk_size_mb=50,
max_threads=5
):
"""
Upload a large file to S3 in parallel using multipart upload.
:param file_path: Local path of the file to upload
:param bucket_name: S3 bucket name
:param object_key: S3 object key
:param chunk_size_mb: Size (in MB) for each multipart chunk
:param max_threads: Number of parallel threads to use
"""
s3_client = boto3.client('s3')
file_size = os.path.getsize(file_path)
chunk_size = chunk_size_mb * 1024 * 1024 # convert MB to bytes
part_count = math.ceil(file_size / chunk_size)
# 1. Initiate multipart upload
resp = s3_client.create_multipart_upload(Bucket=bucket_name, Key=object_key)
upload_id = resp['UploadId']
print(f"Initiated multipart upload. UploadId: {upload_id}")
# 2. Function to upload a single part
def upload_part(part_number, offset):
with open(file_path, 'rb') as f:
f.seek(offset)
data = f.read(chunk_size)
response = s3_client.upload_part(
Bucket=bucket_name,
Key=object_key,
PartNumber=part_number,
UploadId=upload_id,
Body=data
)
etag = response['ETag']
print(f"Uploaded part {part_number}, ETag: {etag}")
return {"PartNumber": part_number, "ETag": etag}
# 3. Submit upload tasks in parallel
futures = []
parts = []
with ThreadPoolExecutor(max_workers=max_threads) as executor:
for part_number in range(1, part_count + 1):
offset = (part_number - 1) * chunk_size
futures.append(executor.submit(upload_part, part_number, offset))
for future in as_completed(futures):
parts.append(future.result())
# Sort parts by PartNumber (required by S3)
parts = sorted(parts, key=lambda x: x["PartNumber"])
# 4. Complete the multipart upload
try:
result = s3_client.complete_multipart_upload(
Bucket=bucket_name,
Key=object_key,
UploadId=upload_id,
MultipartUpload={'Parts': parts}
)
print(f"Multipart upload completed. ETag: {result['ETag']}")
except Exception as e:
print(f"Error completing multipart upload: {e}. Aborting...")
s3_client.abort_multipart_upload(
Bucket=bucket_name,
Key=object_key,
UploadId=upload_id
)
raise
if __name__ == "__main__":
# Replace these values before running:
file_path = "/path/to/large_file.dat"
bucket_name = "your-s3-bucket"
object_key = "backup/large_file.dat"
# Only do multipart for files > 100 MB (optional check)
if os.path.getsize(file_path) <= 100 * 1024 * 1024:
raise ValueError("File must be larger than 100 MB for multipart upload.")
multipart_upload(
file_path=file_path,
bucket_name=bucket_name,
object_key=object_key,
chunk_size_mb=50, # each part is 50 MB
max_threads=5 # upload 5 parts in parallel
)
How it works
- Initialize multipart upload with
create_multipart_upload to get an UploadId.
- Split the file into chunks of
chunk_size_mb.
- Upload each part in parallel using
ThreadPoolExecutor. Each part has an increasing PartNumber starting at 1.
- Complete the upload with
complete_multipart_upload using the collected ETags in order.
- If something fails before completion, the script aborts the upload so you don’t incur partial charges.
Notes
- Minimum part size is 5 MB (except the final part).
- Maximum number of parts is 10,000.
- Make sure your AWS credentials and region are configured (e.g., via environment variables or AWS CLI config).
- Adjust
chunk_size_mb and max_threads based on your network and performance needs.