Backend & Full Stack Engineer: Designing Asynchronous GraphQL File Upload Mutations & Direct-to-Object-Storage Streams
Handling file uploads in a GraphQL API requires choosing the right architecture for payload size and security. Base64-encoding a 25 MB PDF inside a JSON GraphQL variable inflates payload size by 33% and blocks Python ASGI event loops during JSON parsing. As a Backend Engineer and Full Stack Engineer, I implement two complementary GraphQL upload patterns in Python (Strawberry / Ariadne): streaming chunked multipart uploads for small server-validated documents (such as BOM spreadsheets) and cryptographically signed S3 / Google Cloud Storage PUT URLs for large media assets.
1. Non-Blocking Streaming Multipart Validation with Magic-Byte Inspection
When processing small multipart uploads directly in an async Python GraphQL resolver, never call await upload.read() without a byte cap or trust the client-supplied Content-Type header. We stream fixed 64 KB chunks, verify the file's magic-byte signature (e.g., %PDF- or ZIP/XLSX headers), and compute an on-the-fly SHA-256 checksum:
import hashlib
import strawberry
from strawberry.file_uploads import Upload
MAX_UPLOAD_BYTES = 10 * 1024 * 1024 # 10 MB ceiling for direct multipart mutations
PDF_MAGIC_PREFIX = b"%PDF-"
@strawberry.type
class UploadedDocumentReceipt:
sha256_hex: str
size_bytes: int
storage_key: str
@strawberry.type
class Mutation:
@strawberry.mutation
async def upload_verified_pdf(self, file: Upload) -> UploadedDocumentReceipt:
hasher = hashlib.sha256()
total_bytes = 0
first_chunk = True
chunks: list[bytes] = []
while True:
chunk = await file.read(65536)
if not chunk:
break
if first_chunk:
if not chunk.startswith(PDF_MAGIC_PREFIX):
raise ValueError("Invalid file signature: expected PDF document")
first_chunk = False
total_bytes += len(chunk)
if total_bytes > MAX_UPLOAD_BYTES:
raise ValueError("File exceeds 10 MB direct upload limit; use presigned URL mutation")
hasher.update(chunk)
chunks.append(chunk)
digest = hasher.hexdigest()
storage_key = f"uploads/pdf/{digest}.pdf"
await persist_to_object_storage_async(storage_key, b"".join(chunks))
return UploadedDocumentReceipt(sha256_hex=digest, size_bytes=total_bytes, storage_key=storage_key)
2. Direct-to-S3 / GCS Presigned Upload Mutations for Large Assets
For files larger than 10 MB (such as high-resolution video or medical DICOM imagery), our GraphQL mutation issues a content-length-bounded, SHA-256-locked presigned URL so the browser uploads bytes directly to Google Cloud Storage or AWS S3—integrating with our Django & Angular/Next.js GraphQL architecture and real-time BOM spreadsheet ingestion engine.
Need a Backend Engineer or Full Stack Engineer to optimize your GraphQL file upload and cloud storage pipelines? Book a 1-Day Engineering Sprint.