File uploads are a common feature in Django applications. Users upload profile pictures, documents, spreadsheets, videos, reports, and other files. While handling a few small files is usually straightforward, accepting large files or processing multiple uploads simultaneously can create serious memory problems.
A Django application may work correctly during development but start consuming excessive memory when deployed to production. Under heavy traffic, multiple users may upload files at the same time. If the application reads entire files into memory, creates additional copies, or processes them without limits, memory consumption can grow quickly.
For example, imagine a Django application that receives a 100 MB file from ten users simultaneously. If the application loads every file completely into memory, it could require approximately 1 GB just for the uploaded file contents. The actual memory requirement may be higher because of Python objects, request processing, file conversion, and other application operations.
Django provides built-in upload handlers that help prevent this problem by storing smaller uploads in memory and larger uploads in temporary files. However, developers must understand how these handlers work and how to use them correctly.
This article explains how Django processes uploaded files, how to configure upload limits, how to process files in chunks, and how to prevent memory exhaustion in production environments.
Understanding How Django Handles File Uploads
Django uses upload handlers to process files received through HTTP requests.
When a browser uploads a file using a multipart form, Django processes the incoming request and makes uploaded files available through request.FILES.
By default, Django uses two upload handlers:
FILE_UPLOAD_HANDLERS = [
"django.core.files.uploadhandler.MemoryFileUploadHandler",
"django.core.files.uploadhandler.TemporaryFileUploadHandler",
]
These handlers have different responsibilities.
MemoryFileUploadHandler
MemoryFileUploadHandler handles smaller uploads by storing their contents in memory.
For example, when a user uploads a small profile image, Django may keep the uploaded content in a memory-backed file object.
This approach is fast because Django does not need to write the uploaded content to a temporary file immediately.
However, storing large uploads in memory can create problems when several requests arrive simultaneously.
TemporaryFileUploadHandler
TemporaryFileUploadHandler handles uploads that are not processed by the memory handler.
It writes incoming file data to a temporary file on the server instead of keeping the complete file contents in application memory.
On a typical Linux server, temporary files may be stored under /tmp, depending on the operating system and Django configuration.
This approach reduces the amount of memory needed to hold uploaded file contents.
Django's default behavior is designed to handle both small and large uploads without requiring developers to implement their own upload processing mechanism.
Understanding Important Django Upload Settings
Django provides several settings that control upload behavior. Understanding the difference between these settings is important because they do not all limit the same thing.
FILE_UPLOAD_MAX_MEMORY_SIZE
This setting determines the maximum request upload size that Django's memory upload handler will handle in memory.
Its default value is 2.5 MB, or 2,621,440 bytes.
Configure it in settings.py:
FILE_UPLOAD_MAX_MEMORY_SIZE = 2 * 1024 * 1024
With this configuration, the memory upload handler is limited to requests within approximately 2 MB. Larger uploads are handled through temporary-file storage.
This setting does not reject large files. It controls when Django switches from memory handling to temporary-file handling.
DATA_UPLOAD_MAX_MEMORY_SIZE
This setting controls the maximum request data size checked when Django accesses request.body or request.POST.
Its default value is also 2.5 MB.
For example:
DATA_UPLOAD_MAX_MEMORY_SIZE = 5 * 1024 * 1024
One important detail is that when Django accesses request.POST, the size check excludes uploaded file data. When it accesses request.body, the check applies to the complete raw request payload, including file data.
Therefore, DATA_UPLOAD_MAX_MEMORY_SIZE should not be treated as a general maximum file upload size.
Under ASGI, the request may already have been spooled to disk before Django applies this check. This is one reason external request-size limits are important.
FILE_UPLOAD_TEMP_DIR
This setting specifies where Django stores temporary uploaded files.
For example:
FILE_UPLOAD_TEMP_DIR = "/var/tmp/django-uploads"
Create the directory and ensure that the Django application process has permission to write to it.
For production deployments, use a dedicated temporary storage location with sufficient disk capacity and appropriate permissions.
Avoid using a temporary directory that shares limited storage with unrelated application workloads.
Comparing Upload Settings
Setting | Purpose | Default |
|---|
FILE_UPLOAD_MAX_MEMORY_SIZE
| Controls when upload handling switches from memory to temporary-file storage | 2.5 MB |
DATA_UPLOAD_MAX_MEMORY_SIZE
| Limits request data checked through request.body or request.POST | 2.5 MB |
FILE_UPLOAD_TEMP_DIR
| Defines the temporary upload directory | System temporary directory |
FILE_UPLOAD_HANDLERS
| Defines the handlers used to process uploaded files | Memory and temporary-file handlers |
DATA_UPLOAD_MAX_NUMBER_FILES
| Limits the number of files in a multipart POST request | 100 |
The most important distinction is that a memory threshold is not the same as an upload rejection limit.
If your application must reject files larger than 50 MB, you need explicit validation and request-size controls in addition to Django's memory settings.
Configuring Django for Large File Uploads
A practical configuration should control memory usage, temporary storage, and the number of files accepted in a request.
For example:
# settings.py
FILE_UPLOAD_MAX_MEMORY_SIZE = 2 * 1024 * 1024
DATA_UPLOAD_MAX_MEMORY_SIZE = 5 * 1024 * 1024
FILE_UPLOAD_TEMP_DIR = "/var/tmp/django-uploads"
DATA_UPLOAD_MAX_NUMBER_FILES = 10
This configuration provides several protections:
Requests handled by the memory upload handler are limited to approximately 2 MB.
Request data checked through request.body or request.POST is limited to 5 MB, excluding uploaded files from the request.POST file-size calculation.
Larger uploads can use temporary-file storage.
A multipart request cannot contain more than ten uploaded files.
The application still needs a separate file-size validation policy.
For example, if the application accepts documents up to 50 MB, enforce that limit in the upload endpoint and at the reverse proxy or web server.
Do not set DATA_UPLOAD_MAX_MEMORY_SIZE to None simply to allow large uploads. Disabling request-data checks can increase the risk of resource exhaustion.
Avoid Reading Entire Files Into Memory
One of the most common causes of memory exhaustion is reading the complete uploaded file using read().
Consider this Django view:
from django.http import JsonResponse
from django.views.decorators.http import require_POST
@require_POST
def upload_document(request):
uploaded_file = request.FILES["document"]
file_content = uploaded_file.read()
process_document(file_content)
return JsonResponse({
"message": "Upload completed"
})
The problem is this line:
file_content = uploaded_file.read()
It loads the complete file into memory.
If the uploaded file is 200 MB, the application may allocate approximately 200 MB just for its contents. If multiple requests execute simultaneously, memory usage can increase quickly.
A better approach is to process the file in smaller chunks.
Using UploadedFile.chunks()
Django provides the chunks() method to read uploaded files in manageable pieces.
from django.http import JsonResponse
from django.views.decorators.http import require_POST
@require_POST
def upload_document(request):
uploaded_file = request.FILES["document"]
for chunk in uploaded_file.chunks():
process_chunk(chunk)
return JsonResponse({
"message": "File processed successfully"
})
The chunks() method avoids loading the entire file into memory at once.
Django's default chunk size is designed to keep memory consumption manageable. You can also specify a chunk size when necessary.
For example:
for chunk in uploaded_file.chunks(chunk_size=1024 * 1024):
process_chunk(chunk)
This processes the file in chunks of approximately 1 MB.
The exact memory requirement depends on what process_chunk() does. If the processing function stores every chunk in a list, the application can still consume memory proportional to the complete file size.
The important principle is to process and release each chunk before reading the next one.
Saving Uploaded Files Without Loading Them Into Memory
When the application only needs to store an uploaded file, Django's storage system can handle the operation.
For example, consider a model that stores uploaded documents:
from django.db import models
class Document(models.Model):
title = models.CharField(max_length=200)
file = models.FileField(
upload_to="documents/"
)
uploaded_at = models.DateTimeField(
auto_now_add=True
)
A form can receive and validate the uploaded file.
from django import forms
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = ["title", "file"]
def clean_file(self):
uploaded_file = self.cleaned_data["file"]
max_size = 50 * 1024 * 1024
if uploaded_file.size > max_size:
raise forms.ValidationError(
"File size cannot exceed 50 MB."
)
return uploaded_file
The view can then save the validated object:
from django.http import JsonResponse
from django.views.decorators.http import require_POST
@require_POST
def upload_document(request):
form = DocumentForm(
request.POST,
request.FILES
)
if not form.is_valid():
return JsonResponse(
{
"errors": form.errors
},
status=400
)
document = form.save()
return JsonResponse({
"message": "Document uploaded successfully",
"document_id": document.id
})
Django's file handling and storage abstractions support uploaded files without requiring the application to call read() and create a complete in-memory copy.
For large files, this is generally preferable to manually reading the complete file and assigning its contents to a model field.
The example enforces a 50 MB application-level limit. It should be combined with a web server or reverse-proxy request-size limit.
Processing Files With a Custom Upload Handler
Sometimes the default upload handlers are not sufficient.
For example, an application may need to:
Enforce upload quotas while data is arriving.
Track upload progress.
Reject files before the complete upload is received.
Stream data to external storage.
Perform custom processing during upload.
Django supports custom upload handlers for these requirements.
A custom handler can receive uploaded data in chunks.
Consider this example:
from django.core.files.uploadhandler import FileUploadHandler
from django.core.files.uploadhandler import StopUpload
class UploadLimitHandler(FileUploadHandler):
max_upload_size = 50 * 1024 * 1024
def __init__(self, request=None):
super().__init__(request)
self.total_received = 0
def receive_data_chunk(self, raw_data, start):
self.total_received += len(raw_data)
if self.total_received > self.max_upload_size:
raise StopUpload(connection_reset=True)
return raw_data
def file_complete(self, file_size):
return None
The handler tracks the total amount of file data received and stops processing when the configured limit is exceeded.
Returning None from file_complete() allows a later upload handler to produce the final uploaded file.
This handler is a simplified example. A production implementation should consider multiple files, request-wide limits, cleanup behavior, error reporting, and the interaction with other upload handlers.
Registering a Custom Upload Handler
Upload handlers can be configured globally:
FILE_UPLOAD_HANDLERS = [
"myapp.upload_handlers.UploadLimitHandler",
"django.core.files.uploadhandler.MemoryFileUploadHandler",
"django.core.files.uploadhandler.TemporaryFileUploadHandler",
]
However, if the handler needs user-specific settings or request-specific behavior, it can be attached to the request before Django accesses request.FILES.
For example, middleware can configure a handler before the request body is parsed:
class UploadHandlerMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.path == "/upload/":
request.upload_handlers.insert(
0,
UploadLimitHandler(request)
)
return self.get_response(request)
The handler must be added before accessing request.POST or request.FILES. Once Django has parsed the multipart request, changing the upload handlers is too late.
A custom handler should complement external request-size limits, not replace them.
Using Background Tasks for Expensive File Processing
Another common problem occurs when an upload endpoint performs expensive operations before returning a response.
For example, an application may accept a large CSV file and immediately perform these operations:
Read and validate every row.
Transform the data.
Execute database operations.
Generate reports.
Send notifications.
This increases request duration and may keep large amounts of data alive in memory.
A better design is to separate file reception from expensive processing.
The upload endpoint can save the file and create a background job.
For example, using Celery:
from django.http import JsonResponse
from django.views.decorators.http import require_POST
from .models import Document
from .tasks import process_document_task
@require_POST
def upload_document(request):
form = DocumentForm(
request.POST,
request.FILES
)
if not form.is_valid():
return JsonResponse(
{"errors": form.errors},
status=400
)
document = form.save()
process_document_task.delay(document.id)
return JsonResponse({
"message": "File uploaded successfully",
"document_id": document.id,
"status": "processing"
}, status=202)
The background task can retrieve the saved file and process it separately.
from celery import shared_task
from .models import Document
@shared_task
def process_document_task(document_id):
document = Document.objects.get(
id=document_id
)
with document.file.open("rb") as file:
for chunk in iter(
lambda: file.read(1024 * 1024),
b""
):
process_chunk(chunk)
This example reads the stored file in 1 MB chunks.
The web request no longer needs to perform the complete processing operation.
For production systems, consider retry behavior, task idempotency, file cleanup, and what happens when a task fails after the file has been saved.
Also, do not assume that background processing automatically solves memory exhaustion. A worker can still run out of memory if it loads the entire file or processes too many files simultaneously.
Using Direct-to-Cloud Storage Uploads
For applications that accept very large files, uploading directly to object storage can reduce the workload on Django servers.
Instead of sending the entire file through the Django application, the application generates a temporary upload URL. The browser uploads the file directly to a storage service such as Amazon S3 or Azure Blob Storage.
A simplified flow looks like this:
Browser
|
| 1. Request upload authorization
v
Django API
|
| 2. Generate temporary upload URL
v
Browser
|
| 3. Upload file directly
v
Cloud Object Storage
|
| 4. Notify Django about completion
v
Django API
|
| 5. Validate and register file
v
Database
This approach reduces the amount of file data passing through Django application workers.
A typical implementation requires:
User authentication before generating the upload URL.
A unique object key for each upload.
A short expiration time for the upload URL.
Storage-side size and content restrictions where supported.
Validation after upload.
Cleanup of incomplete or abandoned uploads.
The application should not trust the browser's completion notification alone. It should verify that the uploaded object exists and meets the expected requirements.
Direct uploads are especially useful for video platforms, document management systems, backup applications, and other services that handle large files frequently.
Limiting Concurrent Uploads
Even when each individual upload uses limited memory, a large number of simultaneous uploads can exhaust available resources.
For example, suppose each active request requires approximately 5 MB of application memory for upload processing. If 200 requests execute concurrently, the application may require approximately 1 GB for those operations alone.
The actual memory usage will also include Python, Django, application objects, database connections, and other processes.
Therefore, configure concurrency limits at different infrastructure levels.
Configure Web Server Upload Limits
For Nginx, use client_max_body_size:
server {
listen 80;
server_name example.com;
client_max_body_size 50M;
location / {
proxy_pass http://django_backend;
}
}
This rejects requests larger than 50 MB before they reach the Django application.
The value should match the application's upload policy.
For Apache, the equivalent request-body restriction can be configured using LimitRequestBody.
Do not rely only on Django's upload settings to protect the application from oversized requests. Django's security guidance recommends enforcing reasonable upload limits at the web server level.
Configure Application Worker Limits
The number of application workers also affects memory consumption.
For example, a Gunicorn deployment might use:
gunicorn myproject.wsgi:application \
--workers 4 \
--threads 2 \
--timeout 120
This is only an example configuration. The correct worker and thread counts depend on available memory, CPU capacity, request duration, and the application's workload.
Increasing worker count without measuring memory usage can make the problem worse.
Monitor worker memory consumption and configure container or process limits based on realistic load tests.
Managing Temporary Upload Storage
When Django writes large files to temporary storage, disk capacity becomes another important resource.
A system may have enough RAM but still fail because its temporary directory runs out of space.
Configure a dedicated upload directory:
FILE_UPLOAD_TEMP_DIR = "/var/tmp/django-uploads"
For production deployments, consider the following:
Allocate sufficient temporary disk space.
Monitor disk usage.
Restrict directory permissions.
Clean up abandoned temporary files.
Avoid storing permanent application files in temporary directories.
Use separate storage volumes when upload traffic is high.
Temporary upload files are normally managed by Django's upload handling lifecycle. However, infrastructure failures, interrupted requests, and operational mistakes can still create storage problems.
Monitor the temporary directory and include disk usage in application health monitoring.
Testing File Uploads Under Load
A file upload implementation should be tested with realistic file sizes and concurrent requests.
Testing only a small image uploaded by one user does not reveal how the application behaves under production traffic.
Use different test scenarios:
Test scenario | What to verify |
|---|
Small file upload | Memory handling works correctly |
Medium file upload | Upload processing remains stable |
Large file upload | Temporary-file handling works correctly |
Maximum allowed file | Application accepts the expected boundary |
Oversized file | Request is rejected |
Multiple simultaneous uploads | Memory remains within limits |
Interrupted upload | Temporary resources are cleaned up |
Disk pressure | Application handles temporary storage failures |
Monitoring Memory Usage
On Linux, use tools such as top, htop, and container metrics to monitor memory consumption.
For Docker:
docker stats
This provides information about container memory and CPU usage.
For Kubernetes:
kubectl top pods
Use these metrics while running upload tests.
Pay attention to memory usage during simultaneous uploads rather than looking only at average memory consumption.
For more detailed Python analysis, tools such as tracemalloc can help identify Python memory allocations.
import tracemalloc
tracemalloc.start()
# Execute file processing operation.
current, peak = tracemalloc.get_traced_memory()
print("Current memory:", current)
print("Peak memory:", peak)
tracemalloc.stop()
tracemalloc tracks Python memory allocations, but it does not account for every native allocation or total process memory. Combine it with operating-system and container-level monitoring.
Common Mistakes That Cause Memory Exhaustion
Reading the Complete File
Calling uploaded_file.read() without considering file size can load the entire upload into memory.
Use chunks() or another bounded streaming approach when processing large files.
Increasing the Memory Threshold Too Much
Increasing FILE_UPLOAD_MAX_MEMORY_SIZE may seem like a way to improve upload performance, but it can increase memory consumption when many users upload files simultaneously.
Keep the threshold appropriate for the application's workload.
Confusing Request Limits With File Limits
DATA_UPLOAD_MAX_MEMORY_SIZE is not a general maximum file size setting.
Use application-level file validation and web server request-size limits to enforce upload policies.
Ignoring Temporary Disk Usage
Large files are written to temporary storage by the default upload handlers.
If the temporary directory is too small, uploads can fail even when application memory is available.
Processing Files Inside the Request
Expensive processing increases request duration and resource usage.
Move long-running operations to background workers when the application does not need to complete them before responding.
Trusting File Extensions
A file named report.pdf is not necessarily a valid PDF.
Validate file content, use appropriate file-type detection, and apply security controls before processing or serving uploaded content.
Allowing Unlimited Concurrent Uploads
A memory-efficient implementation can still fail if the server accepts more simultaneous requests than its resources can handle.
Set appropriate request concurrency, worker, and infrastructure limits.
Best Practices for Production Django Applications
Keep FILE_UPLOAD_MAX_MEMORY_SIZE at a reasonable value.
Use TemporaryFileUploadHandler for large uploads through Django's default upload handling.
Use uploaded_file.chunks() instead of reading entire files into memory.
Validate file sizes before saving or processing.
Enforce request-body limits at the reverse proxy or web server.
Configure a dedicated temporary upload directory.
Monitor both memory and temporary disk usage.
Limit the number of files accepted in a single request.
Process large files in background workers when appropriate.
Consider direct-to-cloud uploads for very large files.
Restrict concurrent uploads based on available infrastructure resources.
Validate file content instead of relying only on filenames and extensions.
Test uploads under realistic concurrency.
Avoid disabling Django's request-data protections without a clear reason.
Advantages and Disadvantages of Django's Upload Handling
Advantages
Provides built-in memory and temporary-file upload handlers.
Handles small and large files without requiring custom streaming code.
Supports custom upload handlers.
Integrates with Django forms and model file fields.
Provides chunk-based file processing.
Supports custom temporary upload directories.
Can integrate with cloud storage backends.
Disadvantages
Large uploads still consume temporary disk space.
Default settings may not match every production workload.
Custom processing can still consume excessive memory.
ASGI request handling may spool incoming request data before Django's request-size checks.
High upload concurrency can increase infrastructure resource consumption.
Large files passing through application servers can increase network and processing costs.
Conclusion
Preventing memory exhaustion during Django file uploads requires controlling how files are received, stored, and processed.
Django already provides a useful foundation through MemoryFileUploadHandler and TemporaryFileUploadHandler. Smaller uploads can be handled in memory, while larger uploads are written to temporary files.
However, developers must avoid reading complete files into memory, configure suitable upload limits, monitor temporary storage, and control the number of simultaneous uploads.
For applications that process large documents, videos, or other substantial files, chunk-based processing and background workers provide a more reliable approach. When upload volumes become very high, direct-to-cloud storage can reduce the workload on Django application servers.
The best solution combines Django upload handlers, application-level validation, web server request limits, infrastructure monitoring, and realistic load testing. This keeps file upload functionality reliable even when many users upload large files simultaneously.
Join the conversation! Your thoughts help the community grow.