← Back to Django, page 5

django-0088 · Hard senior

How do you backfill or transform millions of rows in Django without locking the table or exhausting memory?

Process rows in primary-key ranges (for example 5,000 at a time), each in its own short transaction, using update() with expressions or bulk_update() on a chunk, and make the job resumable and idempotent. Avoid loading the whole table, avoid one giant transaction or ALTER with a default that rewrites the table, and run it as a management command or a non-atomic migration, throttled while watching replication lag and locks.

Full answer

Naive approach: for s in Student.objects.all(): s.slug = slugify(s.name); s.save(). On millions of rows it loads everything or keeps a server-side cursor open, issues one UPDATE per row and (in a migration) holds one transaction, locking rows, bloating WAL and delaying other writers.

Better:

  1. Add the new column as nullable (fast, metadata only), deploy code that writes both, then backfill, then add constraints. This is the expand and contract pattern.
  2. Iterate by key range, not OFFSET:
python
last_pk = 0
while True:
    ids = list(Student.objects.filter(pk__gt=last_pk, slug="").order_by("pk").values_list("pk", flat=True)[:BATCH])
    if not ids: break
    Student.objects.filter(pk__in=ids).update(slug=Lower("name"))      # or bulk_update for Python-computed values
    last_pk = ids[-1]
  1. Each batch commits separately: in a migration set atomic = False; in a management command, do not wrap the loop in atomic().
  2. Prefer a single SQL expression per batch (update(slug=Lower("name"))) over fetching rows. If Python must compute values, fetch only needed columns (only() or values_list), compute, then bulk_update(objs, ["slug"], batch_size=1000).
  3. Make it idempotent and resumable: filter on "not yet done" (slug="") so reruns only touch remaining rows, and log the last key.
  4. Throttle: time.sleep(0.1) between batches, or adapt to replication lag and lock waits. Run at off-peak times and set lock_timeout so the job fails fast rather than queueing behind long transactions.
  5. Verify with counts after, then add NOT NULL or constraints using the safe patterns (NOT VALID then VALIDATE on PostgreSQL, via RunSQL).

Do not run heavy data migrations in the deploy migration step if they take minutes; ship them as a separate command or background job. For read-only scans use .iterator(chunk_size=2000), which streams rows and (on PostgreSQL without pgbouncer in transaction pooling mode) uses server-side cursors.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

import time

from django.db import models, connection
from django.db.models.functions import Lower
from django.test.utils import CaptureQueriesContext


class Student(models.Model):
    name = models.CharField(max_length=40)
    slug = models.CharField(max_length=40, blank=True, default="")

    class Meta:
        app_label = "school"


with connection.schema_editor() as editor:
    editor.create_model(Student)

Student.objects.bulk_create([Student(name=f"Student {i:05d}") for i in range(1, 5001)], batch_size=1000)

BATCH = 1000


def backfill():
    last_pk, batches, updated = 0, 0, 0
    while True:
        ids = list(Student.objects.filter(pk__gt=last_pk, slug="").order_by("pk").values_list("pk", flat=True)[:BATCH])
        if not ids:
            return batches, updated
        updated += Student.objects.filter(pk__in=ids).update(slug=Lower("name"))   # one short statement per batch
        batches += 1
        last_pk = ids[-1]
        time.sleep(0)                                                              # throttle point (use a real pause in production)


with CaptureQueriesContext(connection) as ctx:
    print("first run (batches, rows):", backfill())
print("queries:", len(ctx), "(2 per batch plus the final empty check)")
print("second run is a no-op:", backfill())
print(Student.objects.filter(slug="").count(), Student.objects.get(pk=5000).slug)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): first run (batches, rows): (5, 5000) queries: 11 (2 per batch plus the final empty check) second run is a no-op: (0, 0) 0 student 05000

Key points

  • Batch by primary-key ranges; each batch is its own short transaction
  • Prefer one SQL expression per batch over Python loops
  • Make the job idempotent and resumable with a not-done filter
  • Use atomic = False in migrations; throttle and watch locks and lag
  • Expand, backfill, then contract

Common mistakes

  • Looping over objects.all() and calling save() on each row
  • Running a long backfill inside one migration transaction
  • Using OFFSET pagination that gets slower on every batch
  • Making the job non-resumable so a crash means starting over
  • Adding NOT NULL or a default that rewrites the table before the backfill

Follow-ups

  • How would you add a NOT NULL constraint afterwards without a long lock?
  • How do you throttle based on replication lag?
  • Why is expand-and-contract safer than a single migration?

Tips

  • Describe key-range batching
  • Mention atomic = False
  • Say idempotent and resumable