The Real Cost of Failed Large File Uploads
Applications that handle videos, CAD files, datasets or backups routinely deal with files ranging from 500 MB to several gigabytes. A single network blip, browser crash, or server timeout forces the user to restart from byte zero. Support tickets increase, user frustration grows, and conversion rates drop for any product that relies on user-generated content.
Traditional multipart/form-data uploads via Fetch or Axios provide no native way to resume. The browser must hold the entire file in memory or re-read it from disk on every retry. AWS S3 direct uploads using presigned URLs improve throughput but still require custom logic to track completed parts and resume a multipart upload session.
The TUS protocol standardizes resumable uploads over HTTP. It defines precise semantics for creation, status checks, and chunked PATCH transfers that both client and server must follow. By adopting TUS 1.0.0 you gain interoperability with existing clients (Uppy, tus-js-client, Transloadit) and servers while keeping full control of your storage backend.
TUS 1.0.0 Protocol Mechanics
TUS builds on standard HTTP methods and headers. A typical flow starts with a POST request to create an upload resource:
POST /uploads HTTP/1.1
Upload-Length: 2147483648
Upload-Metadata: filename dmlkZW8ubXA0
Tus-Resumable: 1.0.0
The server responds with 201 Created and a Location header pointing to the new upload URL, for example https://api.example.com/uploads/9a7b3c2d1e.
To check progress, the client issues a HEAD request. The server returns the Upload-Offset header indicating how many bytes have been received. The client then sends PATCH requests with Content-Type: application/offset+octet-stream and Upload-Offset matching the current server offset. Each successful PATCH returns an updated Upload-Offset.
Optional extensions supported by most implementations include checksum validation (Upload-Checksum), expiration (Upload-Expires), and concatenation. For production systems handling terabytes of data, the ability to query offset without transferring data again is critical.
Because TUS is transport agnostic, the same client library works against a self-hosted server, a managed service, or a custom implementation mapped to cloud object storage.
Architecture Decisions for Next.js + S3
We map each TUS upload to an S3 multipart upload. When the client creates a TUS resource, the server calls createMultipartUpload on S3 and stores the UploadId, the TUS upload ID, current offset, total length, and owner information in a PostgreSQL table managed by Drizzle ORM.
Subsequent PATCH requests are translated into uploadPart calls. We keep a list of completed ETags and part numbers in the database so we can resume after a failure. On finalization the server issues completeMultipartUpload with the collected parts.
This approach avoids storing partial files on local disk (which does not scale across multiple containers) and leverages S3’s built-in durability and parallel part uploads. Trade-off: S3 charges for each part uploaded even if the final object is never completed, so we implement a cleanup job that aborts stale multipart uploads older than 7 days.
Authentication is enforced on every TUS endpoint using NextAuth.js session tokens passed via Authorization: Bearer. Multi-tenant isolation is achieved by scoping the S3 key prefix with the tenant ID and adding a tenant_id column to the uploads table.
Project Setup and Package Versions
Start with the latest stable tooling as of October 2024:
npx create-next-app@15.0.1 tus-demo --typescript --tailwind --eslint --app --yes
cd tus-demo
npm install @aws-sdk/client-s3@3.645.0 @aws-sdk/s3-request-presigner drizzle-orm@0.33.0 pg@8.13.0
npm install -D drizzle-kit@0.22.8
npm install uppy@4.0.0 @uppy/core@4.0.0 @uppy/tus@4.0.0 @uppy/react@4.0.0
Configure Drizzle against PostgreSQL (Supabase, Neon or self-hosted). Create a drizzle.config.ts pointing to your database URL and run the first migration after defining the schema.
Environment variables needed: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION, S3_BUCKET, DATABASE_URL, NEXTAUTH_SECRET.
Drizzle Schema for Upload Metadata
The uploads table acts as the source of truth for TUS state.
import { pgTable, text, bigint, timestamp, uuid } from 'drizzle-orm/pg-core';
export const uploads = pgTable('uploads', {
id: uuid('id').primaryKey().defaultRandom(),
tusId: text('tus_id').notNull().unique(),
userId: uuid('user_id').notNull(),
tenantId: text('tenant_id').notNull(),
filename: text('filename').notNull(),
contentType: text('content_type'),
totalLength: bigint('total_length', { mode: 'number' }).notNull(),
offset: bigint('offset', { mode: 'number' }).default(0),
s3UploadId: text('s3_upload_id').notNull(),
s3Key: text('s3_key').notNull(),
parts: text('parts').array().default([]), // JSON stringified part data
expiresAt: timestamp('expires_at').notNull(),
completedAt: timestamp('completed_at'),
createdAt: timestamp('created_at').defaultNow(),
});
A separate upload_parts table can be added for higher volume use cases, but storing a JSON array of completed parts (up to 10,000) works for most workloads since a typical video uses fewer than 100 parts.
Run npx drizzle-kit generate:pg and npx drizzle-kit migrate to create the table. Add an index on tusId and (tenant_id, user_id) for fast lookups.
Implementing TUS Endpoints in App Router
Create a route group app/api/tus. The POST handler creates both the TUS resource and the S3 multipart upload.
import { NextRequest } from 'next/server';
import { S3Client, CreateMultipartUploadCommand } from '@aws-sdk/client-s3';
import { db } from '@/lib/db';
import { uploads } from '@/lib/schema';
import { getServerSession } from 'next-auth';
const s3 = new S3Client({ region: process.env.AWS_REGION });
export async function POST(req: NextRequest) {
const session = await getServerSession();
if (!session?.user?.id) return new Response('Unauthorized', { status: 401 });
const uploadLength = parseInt(req.headers.get('upload-length') || '0');
const metadataHeader = req.headers.get('upload-metadata') || '';
const filename = extractMetadata(metadataHeader, 'filename');
const key = `${session.tenantId}/uploads/${crypto.randomUUID()}-${filename}`;
const multipart = await s3.send(new CreateMultipartUploadCommand({
Bucket: process.env.S3_BUCKET,
Key: key,
ContentType: req.headers.get('content-type') || 'application/octet-stream',
}));
const tusId = crypto.randomUUID();
await db.insert(uploads).values({
tusId,
userId: session.user.id,
tenantId: session.tenantId,
filename,
totalLength: uploadLength,
s3UploadId: multipart.UploadId!,
s3Key: key,
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24 * 7),
});
return new Response(null, {
status: 201,
headers: {
Location: `/api/tus/${tusId}`,
'Tus-Resumable': '1.0.0',
'Upload-Offset': '0',
},
});
}
The PATCH handler is more involved. It must validate the supplied offset matches the database record, upload the chunk as an S3 part, update the offset and store the ETag, then return the new offset. HEAD requests simply return current offset and length.
Full implementation spans approximately 180 lines when including error handling, tenant isolation checks, and part number sequencing. The key safety rule is to never trust the client offset—always read the authoritative value from the database inside a transaction before writing a part.
Uppy 4.0 Client Integration
Uppy provides a polished React component and the @uppy/tus plugin that speaks TUS natively.
import Uppy from '@uppy/core';
import Tus from '@uppy/tus';
import { Dashboard } from '@uppy/react';
import '@uppy/core/dist/style.min.css';
import '@uppy/dashboard/dist/style.min.css';
const uppy = new Uppy({
restrictions: {
maxFileSize: 10 * 1024 * 1024 * 1024, // 10 GiB
allowedFileTypes: ['video/*', 'application/zip'],
},
})
.use(Tus, {
endpoint: '/api/tus',
retryDelays: [0, 1000, 3000, 5000],
headers: () => ({
Authorization: `Bearer ${sessionToken}`,
}),
chunkSize: 50 * 1024 * 1024, // 50 MiB chunks balance speed and recovery time
onBeforeRequest: (req) => {
// Add tenant-specific metadata if needed
},
});
export default function UploadPage() {
return (
<Dashboard
uppy={uppy}
showProgressDetails
hideUploadButton={false}
note="Files up to 10 GiB. Uploads are resumable."
/>
);
}
The retryDelays array tells Uppy how to back off after network errors. Because the server stores exact offset and S3 part state, closing the browser and reopening the page 30 minutes later continues exactly where it left off, provided the multipart upload has not expired.
Authentication, Authorization and Tenant Isolation
Every TUS request carries a Bearer token validated by NextAuth. Inside the route handlers we query the uploads table with both tusId and tenantId extracted from the JWT. This prevents users from reading or modifying another tenant’s upload records.
For signed URLs or direct browser-to-S3 uploads we would lose this control; TUS gives us a consistent enforcement point. We also enforce a per-tenant quota by summing totalLength of incomplete uploads before allowing a new creation request.
Rate limiting is applied at the route level using Upstash Ratelimit with a sliding window algorithm (20 requests per minute per IP for the PATCH endpoint) to mitigate abuse.
Error Recovery and User Experience Patterns
Network drops are the most common failure. Uppy automatically retries on 5xx responses and on connection errors using the configured retryDelays. The Dashboard UI shows exact bytes uploaded and estimated time remaining.
On the server, we catch AWS SDK errors such as RequestTimeout and return a 500 with Upload-Offset still reflecting the last successfully persisted byte. The client then resumes from that offset.
For very large files we recommend a “background upload” mode: the user can close the tab and receive an email when processing completes. This requires storing a webhook URL or using Inngest to trigger post-processing (transcoding, virus scanning) once the completedAt timestamp is set.
Common edge cases to handle:
- Client sends overlapping chunks (server must reject with 409 Conflict)
- S3 part size smaller than 5 MiB on the final part (AWS requirement)
- Upload expires while client is still uploading (return 410 Gone)
- Database transaction deadlocks under high concurrency (use SELECT FOR UPDATE)
Scaling and Production Deployment
Because state lives in PostgreSQL and S3, the API routes can be scaled horizontally behind a load balancer. Route handlers in Next.js on Vercel automatically scale, but for self-hosted environments we run the same code on multiple Fly.io or Render instances.
Connection pooling is mandatory. Use postgres.js with Drizzle’s connection pool configuration set to 10–15 connections per instance. Monitor the pg_stat_activity view to ensure you are not exhausting the database’s connection limit.
Cleanup is performed by a daily cron job (Inngest or pg_cron) that finds uploads where expiresAt < now() and calls abortMultipartUpload on S3. This prevents accumulating abandoned multipart uploads that incur storage costs.
Observability is added with OpenTelemetry spans around each S3 call and database query. Metrics exported include uploads started, bytes transferred, average chunk latency, and failure rate per tenant.
Monitoring, Debugging and Observability
Key metrics to track in production:
- Upload completion rate (target > 98 % for files under 2 GiB)
- Average time to first byte and time between chunks
- Frequency of offset mismatches (indicates buggy clients)
- S3 multipart upload count and average parts per upload
Use Sentry to capture exceptions with the TUS ID as a tag so you can correlate a user complaint with the exact database row and S3 UploadId. Log the full HTTP headers of every TUS request at debug level for the first week after launch.
Common production bugs encountered:
- Mismatched
Upload-Offsetbecause the database transaction was not used and two PATCH requests raced. - S3
EntityTooSmallwhen the final part was under 5 MiB and the client did not set theUpload-Lengthcorrectly on creation. - Expired presigned URLs when using a long-lived TUS upload that spanned multiple days (solution: refresh credentials before each PATCH).
Alternatives and Decision Framework
TUS is not the only solution. Direct S3 multipart upload with presigned URLs requires more client-side code but removes the proxy hop. Services like UploadThing, Cloudinary or Mux provide managed resumable uploads with additional features (automatic transcoding, CDN delivery) at a higher price.
Choose TUS when you need:
- Full control over storage location and encryption keys
- Unified upload experience across web, mobile (React Native tus client exists), and desktop apps
- Compliance requirements that prohibit third-party upload processors
- Cost predictability—pay only for S3 storage and transfer, not a per-upload SaaS fee
For files under 100 MiB the added complexity of TUS is rarely justified. For anything larger, especially video or dataset uploads, the resumability and standardized client libraries quickly pay for the implementation effort.
The complete working example, including migrations, full route handlers, React component, cleanup cron, and Terraform for the S3 bucket policy, is available in the companion GitHub repository linked at the end of this article. The repository also contains load tests using k6 that simulate 50 concurrent 4 GiB uploads with random network drops to validate recovery behavior.
By combining the TUS protocol, Drizzle-tracked S3 multipart uploads, and a polished Uppy interface, you give users a reliable experience even on unreliable networks while maintaining security, observability, and cost control in production.
