Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 157/ 160
08. Backend

File Uploads to S3

Presigned uploads for documents that feed RAG and multimodal pipelines.

BeginnerPresigned URL · Object Storage3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Instead of sending a big file through your server, the server gives the user a special temporary link so they can put the file straight into storage, and then the server checks it afterwards.

Think of it like…

A drop-box at a secure facility. The front desk checks your ID and gives you a one-time pass for one specific locker for five minutes; you put the package in yourself, and a separate inspection team examines it before it enters the building.

Where you’ve seen it

The knowledge-base product accepts PDFs up to 50 MB. If every upload went through the API, 100 uploads a minute at 50 MB would mean 5,000 MB a minute, 83 MB a second of bandwidth and open connections held for the whole transfer. Instead the client calls POST /v1/uploads with the filename, size and content type; the API checks the user's plan and quota, rejects types outside an allow-list (PDF, DOCX, TXT, PNG), generates the key tenants/{tenant_id}/uploads/{uuid} (never the user's filename, which is stored as metadata) and returns a presigned POST valid for 300 seconds with conditions: content-length-range 1 byte to 50 MB, the exact Content-Type, the exact key and a required x-amz-checksum-sha256. The browser uploads directly (a 20 MB file at 10 MB/s takes about 2 seconds). Files over 100 MB use multipart upload: a 1 GB file in 16 MB parts is 64 parts (parts must be between 5 MB and 5 GB, up to 10,000 parts), uploaded in parallel with each part individually presigned and retried on failure; a lifecycle rule aborts incomplete multipart uploads after 7 days to stop silent storage costs. The bucket has Block Public Access on, SSE-KMS encryption, versioning and a CORS rule allowing only the app's origin to PUT/POST. Objects land in an incoming/ prefix; an S3 event notification goes to a queue, where a worker verifies the magic bytes (a file named .pdf must start with %PDF), scans for malware, enforces page and size limits, extracts text, and only then copies the object to clean/ and starts chunking and embedding; failures move the file to quarantine/ and notify the user. The processing handler is idempotent on (bucket, key, version_id) since S3 events can repeat. The database tracks upload_id, state (pending, uploaded, scanned, indexed, rejected), checksum and owner, and a daily job deletes pending uploads that never completed.

Words you’ll hear

Presigned URL
A time-limited URL (or POST policy) that authorises one specific upload without exposing credentials.
Multipart upload
Uploading a large object in separately transferred parts that S3 assembles.
Content-length-range
A policy condition that bounds the accepted object size.
Quarantine
A holding location where uploads stay until scanning and validation pass.

Visual diagram

Loading interactive diagram

Theory & deep dive

Presigned uploads and the constraints that matter

A presigned PUT URL signs a single request (method, bucket, key, headers) for a limited time; a presigned POST carries a signed policy that can express conditions such as content-length-range, an exact Content-Type, a key prefix and a checksum, which is better when you need to bound size. The API issues the signature after its own checks: authentication, tenant quota, allowed types, declared size. Keep the expiry short (about 5 minutes), bind the URL to one server-generated key (tenants/{tenant_id}/uploads/{uuid}) and store the original filename as metadata, so users can't overwrite each other's objects, traverse paths or guess names. A leaked URL lets anyone upload to that key until it expires, so don't log it and keep scope narrow.

Bucket settings carry much of the security: Block Public Access on, no public ACLs, encryption at rest (SSE-KMS), versioning for recovery, a CORS rule limited to your origin and methods, and lifecycle rules to abort incomplete multipart uploads (after 7 days) and expire temporary prefixes. Integrity: have the client send a SHA-256 checksum and require it in the policy, so corrupted or swapped files are rejected, and use the checksum for deduplication. Remember that the multipart ETag is not a simple MD5 of the file.

Policy conditions

{"expiration": "+300s", "conditions": [{"bucket": "kb-uploads"}, ["eq", "$key", "tenants/t77/uploads/3f9a..."], ["content-length-range", 1, 52428800], ["eq", "$Content-Type", "application/pdf"]]} allows exactly one 1 B to 50 MB PDF at one key for five minutes.

Key takeaway: Sign narrow, short-lived permissions with size, type and key constraints and keep the bucket private and encrypted.

Large files, scanning and downstream processing

Multipart upload splits big files into parts of 5 MB to 5 GB (up to 10,000 parts); 1 GB in 16 MB parts is 64 parts. The client uploads parts in parallel, retries failed parts individually and finishes with a complete call, which makes uploads resumable on flaky networks; presign each part (or use a signed session) rather than the whole object. Add a lifecycle rule to abort incomplete uploads, otherwise orphaned parts bill silently. Bandwidth economics favour direct upload: at 100 uploads a minute of 50 MB each, proxying would carry 5,000 MB a minute (83 MB per second) through your API tier, whereas presigned uploads cost it a few kilobytes of JSON per upload.

Treat every upload as untrusted input. Land objects in a staging prefix, let storage events trigger a queue consumer that verifies magic bytes (not just the extension), runs malware scanning, enforces page, size and complexity limits (a zip bomb or a 10,000-page PDF can exhaust workers) and checks for prompt-injection payloads before text reaches your retrieval index. Only then move the object to a clean prefix and start parsing, chunking and embedding. Make the handler idempotent on (bucket, key, version_id), because S3 events are at-least-once, and track state in your database (pending → uploaded → scanned → indexed | rejected) with cleanup for abandoned uploads. Tag objects with tenant, owner and retention so deletion requests (erasing a user's data, including derived chunks and embeddings) can be honoured.

Multipart arithmetic

1 GB file, 16 MB parts: 1,024 / 16 = 64 parts, uploaded 4 at a time. Retrying part 17 alone costs 16 MB, not 1 GB. Limits: 5 MB ≤ part ≤ 5 GB, at most 10,000 parts, so the 16 MB part size supports objects up to about 160 GB.

Key takeaway: Use multipart for large files, scan and validate in a staging area and keep processing idempotent and traceable to the owner.

How it works, step by step

Step 1 of 4
API

1. Authorise and sign

Check identity, quota, type and size, then return a short-lived presigned POST for a server-generated key.

300 s · 1 B–50 MB · exact type
Key numbers at this step
Store
filename as metadata

When to use it & trade-offs

What it is

Letting users upload documents, audio or images for RAG and multimodal pipelines is safest and cheapest when the bytes go directly to object storage instead of through your API. The pattern uses a presigned URL: your API authenticates the caller, checks quota and file rules, then asks S3 (or a compatible service) to sign a short-lived URL or POST policy bound to a specific key, size range and content type. The browser uploads straight to the bucket; storage emits an event that triggers scanning, parsing, chunking and embedding in background workers. Large files use multipart upload in parallel parts. The bucket stays private, keys are generated by the server and every object is encrypted.

Why it matters: Proxying files through the API burns bandwidth, memory and request time on work object storage does better, and exposes you to slow uploads that tie up workers. Direct uploads scale, resume and cost less, but they move trust to the edge: the client now writes to your bucket, so size limits, content types, key naming and malware scanning must be enforced by signed constraints and a quarantine step. Uploaded files also feed RAG, so a poisoned or oversized file becomes a security and cost issue downstream.

When to reach for it

  • Document ingestion for RAG
  • Audio, image and video inputs for multimodal features
  • Large datasets and evaluation files

When to avoid or be careful

  • Using user-supplied filenames as object keys
  • Public buckets or public-read ACLs
  • Indexing a file before scanning and validation

Upload approaches

Presigned direct upload
Best for: Most files above a few MB

Strengths: Scales; no API bandwidth; resumable with multipart.

Watch out: Constraints and scanning must be designed carefully.

Proxy through the API
Best for: Tiny files needing inline validation

Strengths: Full control in one place.

Watch out: Bandwidth and worker time; poor for large files.

Resumable upload service (tus or similar)
Best for: Very large or unreliable-network uploads

Strengths: Resume across sessions.

Watch out: Extra service to run.

Interview signals & numbers to know

When this topic comes up

  • “How would you let users upload large PDFs?”
  • Presigned URL versus proxying
  • Multipart upload and its limits
  • Scanning and quarantine
  • Idempotent handling of storage events

Benchmarks & rules of thumb

83 MB/s -
API bandwidth if 100 uploads/min of 50 MB were proxied
300 s -
typical presigned URL lifetime
5 MB – 5 GB, ≤ 10,000 parts -
S3 multipart part size and count limits

Common mistakes & follow-ups

Common interview mistakes

  • Trusting the file extension or declared content type.
  • Leaving incomplete multipart uploads to accumulate cost.
  • Presigning broad prefixes or with very long expiry.

Likely interviewer follow-ups

  • How would you block a malicious file from reaching the index?
  • How do you let users resume a failed 1 GB upload?
  • How do you delete a user's data including derived embeddings?
Interview tip: Describe the quarantine step; uploads feeding RAG are an attack path, and saying so shows security awareness.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply File Uploads to S3 with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Retries with Backoff
Next topic
Pagination