Rails S3 multipart streaming allows you to process large file uploads in real-time by reading individual parts as they arrive, rather than waiting for the entire object to complete. This approach prevents memory exhaustion in your Rails application by avoiding the need to buffer gigabytes of data in RAM. By leveraging the new S3 GetPart API, you can start downstream processing like transcoding or AI analysis immediately after each part lands. This technique is essential for building scalable media pipelines and high-throughput data ingestion systems in modern Ruby on Rails applications.
Why Wait for the Full Upload?
The traditional approach to handling large file uploads in Rails is fundamentally flawed for modern workloads. Most developers wait for the entire multipart/form-data request to finish before processing the file, which ties up server memory and delays user feedback. This bottleneck becomes critical when dealing with files larger than 5GB, where the upload itself can take minutes or hours.
The new S3 GetPart API changes this dynamic entirely. It allows your application to read a specific part of a multipart upload as soon as it is available, even while the rest of the file is still being transferred. This means you can begin processing the first chunk of a video file while the user is still uploading the last chunk.
This shift from batch processing to stream processing is not just an optimization; it is an architectural necessity for scalable systems. If you are building a media platform, a backup service, or an AI training data pipeline, waiting for the full file is a performance anti-pattern.
How Does the GetPart API Work?
The GetPart API is a new feature in Amazon S3 that exposes individual parts of a multipart upload for immediate reading. Previously, parts were internal to the upload process and inaccessible until the CompleteMultipartUpload call was made. Now, each part is a readable entity with its own ETag and byte range.
When a part is uploaded, S3 emits an s3:MultipartUpload:PartUploaded event notification. Your Rails application can subscribe to this event via SNS or SQS. Upon receiving the notification, your worker can call the GetPart API to fetch that specific part.
This decoupling allows for parallel processing. While the client is still uploading part 5, your server can be transcoding part 3. This parallelism significantly reduces the total time from upload start to processing completion.
Verification note: The availability of the GetPart API and the
s3:MultipartUpload:PartUploadedevent depends on your AWS region and the version of the AWS SDK you are using. Ensure you are using the latest version of theaws-sdk-s3gem to access these features.
Choosing the Right Upload Strategy
Not every upload requires the complexity of multipart streaming. The right strategy depends on file size, latency requirements, and processing needs. Below is a decision matrix to help you choose the appropriate method.
| Strategy | Best For | Pros | Cons |
|---|---|---|---|
| Direct PUT | Files < 5GB, simple use cases | Simplest implementation, low latency | No resumability, memory overhead for large files |
| Multipart (Standard) | Files > 5GB, resumable uploads | Resumable, parallel upload speed | Must wait for full upload before processing |
| Multipart (Streaming) | Large files, real-time processing needs | Process parts as they arrive, lower memory footprint | Complex implementation, requires event handling |
| Presigned URL | Client-side uploads, offloading server | Server never touches data, scales infinitely | Harder to monitor progress, less control over processing |
For most Rails applications, the standard multipart upload is sufficient. However, if you are ingesting large media files for immediate processing, the streaming approach offers a significant advantage. The key trade-off is complexity. Implementing streaming requires handling event notifications and managing part state, which adds code and operational overhead.
If your application is a simple CRUD app with user avatars, stick to direct PUTs. If you are building a video hosting platform, invest in the streaming architecture. The complexity is justified by the performance gains and reduced infrastructure costs.
Implementing Multipart Streaming in Rails
Implementing this in Rails requires a few key components: a controller to initiate the upload, a background job to handle part processing, and a service object to manage the S3 interaction. Below is a practical example using the aws-sdk-s3 gem.
First, set up your S3 client. Ensure your Gemfile includes aws-sdk-s3.
# app/services/s3_streaming_service.rb
class S3StreamingService
attr_reader :client, :bucket
def initialize
@client = Aws::S3::Client.new
@bucket = Rails.application.credentials.aws_s3_bucket
end
def create_multipart_upload(key, content_type)
client.create_multipart_upload(
bucket: bucket,
key: key,
content_type: content_type
)
end
def upload_part(upload_id, part_number, body)
client.upload_part(
bucket: bucket,
key: key,
upload_id: upload_id,
part_number: part_number,
body: body
)
end
def get_part(upload_id, part_number, range = nil)
# Note: In a real app, you would use the object key and part number
# The GetPart API allows reading specific parts by part number
client.get_object(
bucket: bucket,
key: key,
range: range
)
end
endThe controller initiates the upload and returns the upload ID to the client. The client then uploads parts directly to S3 using presigned URLs or the SDK.
# app/controllers/uploads_controller.rb
class UploadsController < ApplicationController
def new
@upload = S3StreamingService.new.create_multipart_upload(
"uploads/#{SecureRandom.uuid}",
params[:content_type]
)
render json: { upload_id: @upload.upload_id }
end
def complete
upload_id = params[:upload_id]
parts = params[:parts] # Array of part numbers
# Verify all parts are present
# Then complete the upload
S3StreamingService.new.complete_multipart_upload(upload_id, parts)
render json: { status: "success" }
end
endThe critical part is the background job that processes each part as it arrives. You can use Active Job with a queue that listens for S3 events.
# app/jobs/process_part_job.rb
class ProcessPartJob < ApplicationJob
queue_as :default
def perform(bucket, key, part_number)
service = S3StreamingService.new
part_data = service.get_part(key, part_number)
# Process the part (e.g., transcode, analyze, store)
MediaProcessor.process(part_data)
end
endTo trigger this job, you need to set up an SNS topic in AWS that sends notifications to an SQS queue. Your Rails application then polls this queue or uses a webhook to trigger the job. This setup requires some AWS configuration but is manageable with tools like aws-sdk-sns and aws-sdk-sqs.
Handling Resumability and Errors
Large file uploads are prone to interruption. Network failures, browser crashes, or server restarts can break the upload process. Multipart uploads are inherently resumable, but you must implement the logic to track progress.
Store the upload ID and the list of completed parts in your database. When the client reconnects, query the database to determine which parts have already been uploaded. The client can then skip those parts and resume from the next one.
# app/models/upload.rb
class Upload < ApplicationRecord
has_many :parts, dependent: :destroy
def completed_parts
parts.pluck(:part_number)
end
def missing_parts(total_parts)
(1..total_parts).to_a - completed_parts
end
endError handling is crucial. If a part fails to upload, the client should retry that specific part. If the entire upload fails, you can abort the multipart upload to clean up incomplete parts.
def abort_upload(upload_id)
client.abort_multipart_upload(
bucket: bucket,
key: key,
upload_id: upload_id
)
endImplement exponential backoff for retries. Do not retry immediately after a failure. Wait for a short period, then retry with increasing delays. This prevents overwhelming the S3 service during transient network issues.
Monitoring and Observability
Streaming uploads introduce new failure modes. Parts can arrive out of order, some parts may fail while others succeed, and the final completion step can fail after all parts are uploaded. You need robust monitoring to detect these issues.
Log every part upload and processing event. Include the upload ID, part number, and timestamp. This allows you to trace the lifecycle of a specific upload. Use structured logging to make it easy to query in your log aggregation system.
Set up alerts for failed parts. If a part fails to process, alert your team immediately. Do not wait for the entire upload to fail. Early detection allows you to intervene before the user experiences a complete failure.
Monitor the queue depth of your part processing jobs. If the queue grows too large, it indicates that your processing capacity is insufficient. Scale your workers or optimize your processing logic.
Use AWS CloudWatch to monitor S3 metrics. Track the number of multipart uploads, the size of parts, and the latency of GetPart calls. This data helps you tune your part size and processing pipeline.
Frequently asked questions
Can I use this with Rails 8?
Yes, the GetPart API is a feature of Amazon S3, not Rails. As long as you are using a recent version of the aws-sdk-s3 gem, it will work with any version of Rails, including Rails 8. The integration points are standard Ruby code, so there are no framework-specific constraints.
What is the minimum part size for multipart uploads?
The minimum part size for all parts except the last one is 5 MB. The last part can be smaller. If you attempt to upload a part smaller than 5 MB, S3 will reject it. This constraint is important for designing your chunking logic on the client side.
How do I handle concurrent uploads?
S3 handles concurrent uploads natively. Multiple parts can be uploaded simultaneously. Your application should be designed to handle part notifications in any order. Use a database lock or a state machine to ensure that the final completion step only occurs when all parts are present and processed.
Is this secure?
Yes, if you use presigned URLs or IAM roles to restrict access. Do not expose your AWS credentials to the client. Use presigned URLs for part uploads and restrict the GetPart API access to your server-side application. This ensures that only your application can read the parts.
What about cross-region uploads?
S3 multipart uploads are region-specific. You cannot start an upload in one region and complete it in another. If your users are distributed globally, consider using S3 Transfer Acceleration or routing uploads to the nearest region. The GetPart API works within the same region as the upload.
Conclusion
Streaming multipart uploads to Amazon S3 in Rails is a powerful technique for handling large files efficiently. By leveraging the GetPart API, you can process data in real-time, reducing memory usage and improving user experience. This approach is essential for media platforms, backup services, and data pipelines.
The implementation requires careful attention to error handling, monitoring, and state management. However, the benefits in scalability and performance are significant. If you are struggling with large file uploads in your Rails application, consider adopting this pattern.
If you are unsure how to implement this in your specific context, or if you need help with the AWS configuration, we can assist you. Book a discovery call to discuss your requirements and explore how we can help you build a robust upload pipeline.
For more insights on scaling Rails applications, check out our guide on Rails API Development or learn about Kamal for Rails 8 for deployment strategies.
See the related service for hands-on help. Primary source: the official project page.


