Reiteach Aigean Logo
Reiteach Aigeanblog.reiteachaigean.com
Admin
HomeAI UpdatesCodingCloudApps & ToolsTech NewsArticles
DjangoCeleryRedis14 min read·23 reads

How to Process Millions of Records Using Celery

Learn how to process millions of records using Celery: chunking, queue design, backpressure, bulk writes, progress tracking, retries, and monitoring.

S
Sizan Mahmud
Published on November 24, 2026
How to Process Millions of Records Using Celery

Introduction

At some point, every backend team gets a job like this: recalculate a field for every row, re-send a notification to every user, migrate data into a new schema, enrich every product through an external API, or re-index an entire table. The dataset has a few million records, and the job has to finish without taking production down.

Celery is a natural fit for this work. It gives you parallelism, retries, and the ability to run outside the web request. But "just put it in Celery" is not a design. A badly designed Celery job can be slower than a plain loop, flood your broker, exhaust your database connections, and leave you with no idea what finished.

This guide covers how to process millions of records using Celery in a way that is fast, restartable, and safe. The examples use Python and the Django ORM, but the patterns apply to any data source.

First Question: Do You Even Need Celery?

Before building a pipeline, ask whether the work can be done in the database.

UPDATE orders
SET total = subtotal + tax - discount
WHERE total IS NULL;

One SQL statement that runs for a minute beats millions of Python function calls. If the transformation can be expressed in SQL, do it there, ideally in batches (for example by ID range) so you do not hold one giant transaction or lock.

Reach for Celery when the work needs Python logic, calls external services, or must run in parallel across machines. Everything below assumes that is your case.

The Rule That Matters Most: Never Make One Task Per Record

The most common mistake is this:

for record_id in Record.objects.values_list("id", flat=True):
    process_record.delay(record_id)

With 5 million records, that sends 5 million messages to the broker. Each message has overhead, Redis keeps queued messages in memory, workers spend more time fetching and acknowledging than working, and a single slow dispatcher loop can take hours.

The fix is chunking: one task handles a batch of records, usually in the range of 1,000 to 5,000. 5 million records become 1,000 to 5,000 tasks, which a broker handles easily.

Design Tasks queued Broker overhead Retry unit
One task per record 5,000,000 Very high One record
2,000 records per task 2,500 Low One chunk
One giant task 1 None Everything

Chunks are the sweet spot: small enough to retry cheaply, large enough that per-task overhead disappears.

Step 1: Split Work by Key Range, Not by OFFSET

How you divide the data matters as much as how big the chunks are. Pagination with OFFSET gets slower the deeper you go, because the database reads and discards every skipped row. Split by an indexed key instead:

from django.db.models import Min, Max

def get_bounds():
    b = Record.objects.aggregate(lo=Min("id"), hi=Max("id"))
    return b["lo"], b["hi"]

Each chunk is then a range query:

Free tech newsletter

Free

Free to join — no card, no paywall. Weekly AI, cloud & tooling insights.

rows = Record.objects.filter(id__gte=start, id__lte=end)

That is a fast index range scan, whether you are at the start of the table or the end. Tasks carry only two integers, so messages stay tiny. If your IDs have large gaps, some chunks will be nearly empty, which is harmless. For extreme gaps, fetch the next batch with filter(id__gt=last_id).order_by("id")[:N].

If your data is not in a database, shard by something stable: file byte offsets or line ranges for a big CSV, S3 object keys or prefixes, or API page cursors. Never pass large payloads through the broker.

Step 2: Process Each Chunk in Bulk

Inside a chunk task, avoid per-row queries:

def process_range(start, end):
    rows = list(
        Record.objects.filter(id__gte=start, id__lte=end)
        .only("id", "subtotal", "tax", "discount")
    )

    updated, failed = [], []
    for row in rows:
        try:
            row.total = calculate_total(row)
            updated.append(row)
        except Exception:
            failed.append(row.pk)  # isolate bad records, don't fail the chunk

    Record.objects.bulk_update(updated, ["total"], batch_size=500)
    return len(rows), failed

A few points make this fast and safe:

  • .only() loads just the columns you need.
  • bulk_update() and bulk_create() replace thousands of single queries with a few batches. They skip save() and signals, so set fields like updated_at yourself.
  • Per-record try/except isolates poison records. One malformed row should not make a whole chunk of 2,000 fail and retry forever.
  • Pass IDs and ranges, not model objects. The worker should always read fresh data.

For the query side of this, including indexes and avoiding N+1 queries inside the loop, see the related reading section below.

Step 3: Control the Flow with Worker "Lanes"

A naive dispatcher queues all 2,500 chunks at once. That works, but it has downsides: every chunk competes for the same workers, you cannot easily limit database pressure, and a bug is replicated 2,500 times before you notice.

A better pattern is a fixed number of lanes. The data is divided into a few segments, and each lane processes its segment one chunk at a time, queueing its own next chunk when the current one succeeds:

from celery import shared_task

@shared_task
def start_job(job_id, lanes=8, chunk=2000):
    lo, hi = get_bounds()
    if lo is None:
        return
    span = (hi - lo) // lanes + 1
    for i in range(lanes):
        seg_lo = lo + i * span
        seg_hi = min(hi, seg_lo + span - 1)
        if seg_lo <= hi:
            process_lane.delay(job_id, seg_lo, seg_hi, chunk)


@shared_task(acks_late=True, ignore_result=True)
def process_lane(job_id, start, seg_hi, chunk):
    end = min(start + chunk - 1, seg_hi)

    try:
        count, failed = process_range(start, end)
        record_progress(job_id, count, failed)
    except Exception:
        record_failed_range(job_id, start, end)  # log it, then keep going

    if end < seg_hi:
        process_lane.delay(job_id, end + 1, seg_hi, chunk)

What this buys you:

  • Built-in backpressure. At most lanes chunks run at once, so the load on your database and external APIs is predictable.
  • A tiny queue. Only a handful of messages exist at any time, instead of thousands.
  • A tunable speed. Raise or lower lanes to go faster or gentler.
  • Crash safety. If a worker dies after finishing a chunk but before queueing the next one, acks_late redelivers the task, the chunk runs again (it must be idempotent), and the lane continues.

If you prefer the simpler "queue everything" approach, that is fine for moderate sizes. Just use a dedicated queue and limit worker concurrency so the job cannot starve other work.

Why You Should Be Careful with group and chord

Celery's canvas primitives are tempting:

from celery import group, chord

chord(group(process_chunk.s(a, b) for a, b in ranges))(finalize.s())

For a few dozen tasks, that is great. For thousands, it has real costs. A chord needs a result backend, stores a result for every task in the group, and its callback only fires when every task has finished, so a single stuck or lost task blocks the finalizer. Large groups also create a large payload at dispatch time.

For millions of records, prefer independent tasks plus a progress counter, and let your own completion check decide when the job is done. Use chain for short sequential steps, and be wary of chunks() on huge iterables, because it needs the full argument list up front.

Step 4: Tune Celery Workers for Bulk Work

Default settings assume many short tasks. Bulk jobs behave differently:

Free tech newsletter

Free

Free to join — no card, no paywall. Weekly AI, cloud & tooling insights.

## settings.py
CELERY_TASK_ACKS_LATE = True
CELERY_TASK_REJECT_ON_WORKER_LOST = True
CELERY_WORKER_PREFETCH_MULTIPLIER = 1
CELERY_TASK_IGNORE_RESULT = True
CELERY_RESULT_EXPIRES = 3600
CELERY_TASK_TIME_LIMIT = 900
CELERY_TASK_SOFT_TIME_LIMIT = 840
CELERY_WORKER_MAX_TASKS_PER_CHILD = 200
## CELERY_WORKER_MAX_MEMORY_PER_CHILD = 500_000  # in KiB (~500 MB)

Why each one matters:

  • acks_late and reject_on_worker_lost: a task whose worker crashes goes back to the queue. This is why idempotency is required.
  • prefetch_multiplier = 1: stops a worker from reserving a pile of long tasks while others sit idle.
  • ignore_result: if you do not read task results, do not store them. Millions of stored results fill your backend for no benefit.
  • Time limits: a stuck task cannot hold a worker forever.
  • max_tasks_per_child and max_memory_per_child: recycle worker processes to contain memory growth from long runs. The memory setting is in kibibytes.

Run bulk work on its own queue so it cannot delay time-sensitive tasks such as password reset emails:

@shared_task(queue="bulk", acks_late=True, ignore_result=True)
def process_lane(...):
    ...
celery -A config worker -Q bulk -c 8 --loglevel=info

Pick the right pool for the work. CPU-heavy tasks suit the default prefork pool, with concurrency near the number of cores. Tasks that mostly wait on network calls, such as enrichment through external APIs, can use a gevent or threads pool with higher concurrency. Do not mix both kinds of work on the same workers.

Step 5: Protect the Database and External Services

Parallelism makes it easy to overwhelm what sits behind your workers.

  • Connections. Each prefork worker process opens its own database connection. Sixteen processes across five machines is 80 connections. Add up the total, keep it under max_connections, and use a pooler when needed.
  • Transactions. Keep them short: one chunk per transaction, never the whole job. Do not hold a transaction open during a network call.
  • Indexes. The columns in your range filter and any lookups inside the loop must be indexed, or each chunk becomes a slow scan.
  • Rate limits. Celery's rate_limit option applies per worker instance, not globally, so with ten workers a limit of 10/s allows about 100 per second in total. For hard global limits on an external API, use a shared token bucket in Redis, or control throughput with the number of lanes.
  • Quiet hours. For heavy backfills on a busy system, run at night or start with fewer lanes and ramp up.

Step 6: Make Everything Idempotent

Between acks_late, retries, and manual re-runs, any chunk may run more than once. A task is idempotent if running it twice gives the same result as running it once.

## Not idempotent: duplicate runs add the bonus twice
Wallet.objects.filter(user_id=uid).update(balance=F("balance") + 10)

## Idempotent: duplicate runs give the same final state
order.total = calculate_total(order)

Compute from source data instead of incrementing, use upserts, and store processed flags or idempotency keys for side effects like emails and payments. This is the single property that makes the entire pipeline restartable.

Step 7: Track Progress and Make the Job Resumable

For a job that runs for hours, "it seems to be working" is not enough. Track three things: how many records are done, which ranges failed, and where to resume.

import redis

r = redis.Redis.from_url(settings.REDIS_URL)

def record_progress(job_id, count, failed):
    r.incrby(f"job:{job_id}:done", count)
    if failed:
        r.rpush(f"job:{job_id}:failed_ids", *failed)

Redis counters are fast and atomic. A database table works well too, using F() expressions to increment counters:

from django.db.models import F

BulkJob.objects.filter(pk=job_id).update(done=F("done") + count)

Store failed ranges and failed record IDs somewhere durable, such as a FailedRange table, so you can replay only what failed once the bug is fixed. Compare done to the total to compute a percentage, and show it on an admin page or dashboard.

Step 8: Retries, Done Right

Transient failures, such as a timeout or a brief database blip, deserve a retry with exponential backoff and jitter. Permanent failures, such as bad data, do not. The per-record try/except above handles the second kind, and Celery's autoretry_for with retry_backoff handles the first. Retrying the whole chunk only makes sense when something external failed.

Monitoring While It Runs

Watch these during a big job:

  • Queue depth. With Redis, LLEN bulk shows how many tasks are waiting. A queue that only grows means workers cannot keep up.
  • Throughput. Records per minute, from your progress counter.
  • Worker health. Flower shows active tasks, failures, and worker status.
  • Database load. Active connections, slow queries, and lock waits.
  • Errors. Send exceptions to Sentry with the chunk range attached, so you can reproduce them.

Estimating How Long It Will Take

Do the arithmetic before you start, using measurements from a small test run:

Free tech newsletter

Free

Free to join — no card, no paywall. Weekly AI, cloud & tooling insights.

chunks = total_records / chunk_size
total_seconds = chunks × seconds_per_chunk / parallel_workers

For example, 5,000,000 records at 2,000 per chunk is 2,500 chunks. If a chunk takes 4 seconds and you run 16 parallel workers, that is roughly 2,500 × 4 / 16 = 625 seconds, a little over 10 minutes. These numbers are illustrative, so measure your own chunk time on realistic data. Then check whether the database can actually sustain that many parallel workers, because the database is usually the real limit.

Choosing a Chunk Size

There is no universal number. Try sizes such as 500, 2,000, and 5,000 on a sample range and record the time per chunk, memory use, and database load. Aim for tasks that last a few seconds to about a minute. Smaller chunks mean cheaper retries and finer progress, and larger chunks mean less overhead. Start around 1,000 to 5,000 and adjust.

Common Mistakes to Avoid

  1. One task per record. It floods the broker and wastes time on overhead.
  2. OFFSET pagination. It gets slower with every page.
  3. Giant chords over thousands of tasks. They are heavy on the result backend and block on the slowest task.
  4. Storing results you never read. Use ignore_result.
  5. No idempotency. Duplicate runs corrupt data.
  6. Letting one bad record fail a whole chunk. Isolate failures per record.
  7. Unlimited parallelism. The database or external API becomes the bottleneck and falls over.
  8. No progress tracking or failure log. You cannot tell what finished or resume safely.
  9. Bulk work sharing a queue with user-facing tasks. Use a dedicated queue.
  10. Skipping a dry run. Test on a small ID range or a copy first.

A Production Checklist

Before running a large job, confirm that:

  • The work cannot be done more simply in SQL
  • Records are processed in chunks of roughly 1,000 to 5,000, not one per task
  • Chunks are split by indexed key range, not by OFFSET
  • Reads use .only(), and writes use bulk operations
  • Parallelism is limited with lanes or concurrency, with a dedicated queue
  • Workers use acks_late, prefetch_multiplier=1, time limits, and ignore_result
  • Tasks are idempotent
  • Bad records are isolated and failed ranges are stored
  • Progress is tracked and the job can resume
  • Total database connections stay under max_connections
  • You tested on a small range and verified the results

Related Reading: Go Deeper on Each Part of the Pipeline

A bulk Celery job touches several parts of your stack. These guides cover each one in more depth:

Conclusion

Processing millions of records with Celery is less about clever code and more about sound structure. Split the data into key-range chunks, process each chunk with bulk operations, limit parallelism so you do not overwhelm what sits behind your workers, and make every task safe to run twice. Add progress tracking and a failure log so the job can be monitored and resumed, and tune workers for long, heavy tasks instead of short, quick ones.

Do that, and a job that would have crashed your server becomes a predictable pipeline you can start, watch, pause, and finish, whether the dataset has a million records or a hundred million.

Frequently Asked Questions

How do I process millions of records with Celery? Split the data into chunks of about 1,000 to 5,000 records using an indexed key range, queue one task per chunk, process each chunk with bulk database operations, and limit parallelism so the database is not overwhelmed. Make tasks idempotent and track progress so the job can resume.

What is the best chunk size for Celery tasks? There is no universal number. A good starting range is 1,000 to 5,000 records per task. Measure time per chunk, memory, and database load on real data, and aim for tasks that run a few seconds to about a minute.

Should I create one Celery task per record? No. One task per record sends millions of messages to the broker and wastes time on overhead. Process records in batches instead, so millions of records become a few thousand tasks.

Why avoid chords for very large jobs? A chord needs a result backend, stores a result for every task in its group, and only runs its callback after every task finishes, so one stuck task blocks the whole thing. For huge jobs, independent tasks with a progress counter are lighter and more robust.

How do I stop a Celery bulk job from overloading my database? Limit concurrency with a dedicated queue and a fixed number of worker lanes, keep transactions short, index the columns you filter on, and add up connections across all worker processes so the total stays under PostgreSQL's max_connections.

Does Celery's rate_limit apply across all workers? No. The rate_limit option applies per worker instance, so ten workers with a limit of 10/s can reach about 100 per second in total. For a hard global limit, use a shared rate limiter such as a Redis token bucket, or control throughput through the number of parallel lanes.

How do I make a Celery bulk job resumable? Make each chunk idempotent, record which ranges completed or failed in a durable store, and use acks_late so tasks from crashed workers are redelivered. Then you can re-run only the failed ranges instead of starting over.

Share this article

Pass this technical dispatch along to fellow engineers

Did you enjoy this article?

Rate it so we know what content to bring next

Comments (0)