How to Update Millions of Database Rows Without Timeouts

An architecture pattern for large data migrations and bulk updates in Java: split the work into small durable jobs, run them in parallel, retry each chunk on its own and continue only when all of them succeeded.

How to Update Millions of Database Rows Without Timeouts

“I need to update millions of rows in a database without the database timing out.”

The classic case: you deploy a new version of your software and the JSON stored in every row needs a new structure. You may know the problem in another shape too. A backfill after a schema change. A recalculation for every customer at the end of the month. Billions of small transactions every week that all have to land.

The challenge

One big statement is the obvious first try, and it fails… Why? The transaction holds its locks for minutes, the statement timeout kicks in, and the database rolls back everything it did so far. Your live traffic waits behind those locks in the meantime.

Splitting the work into smaller pieces is the obvious answer. It only works when:

  • It has to stay out of the way. Locks are held for seconds, not minutes, so live traffic keeps moving while the work runs.
  • It has to remember progress. After a restart, something has to know which pieces are done. Otherwise part of the table is in the new shape, part is in the old shape, and nothing tells you where it stopped.
  • It has to redo only what failed. A deadlock in one piece must not roll back the rest.
  • It has to know when it is finished. The next step, such as verifying the counts or dropping the old column, may only run when every piece succeeded.

The pattern

1PLAN2FAN OUT3FAN INPlanner jobReads the id range,enqueues one job per chunk1,000,000 rows100 chunks of 10,000Chunks only start whenplanning fully succeededPRO100 chunk jobsrows 0 to 9,999SUCCEEDEDrows 10,000 to 19,999PROCESSINGrows 20,000 to 29,999RETRY 2 OF 1097 more chunksENQUEUEDFollow-up jobRuns once, after all100 chunks succeededVerify the row countsSwitch the feature flagTell the teamPROeach chunk is claimed by exactly one worker threadYOUR APPLICATION INSTANCESInstance 1worker threads run chunksInstance 2worker threads run chunksInstance 3worker threads run chunksNeed it done sooner?Start another instanceYOUR SQL DATABASEBusiness tableupdated 10,000 rows per short transactionJobRunr tablesstate, attempts and history of every chunkA chunk failsOnly that chunk retries,with exponential back-offAn instance diesIts chunks are picked upby another instancePeak hoursPause the batch from thedashboard, resume at nightPRO
  1. Plan. One planner job reads the id range of the table and creates one job per chunk, for example 100 jobs that each update 10,000 rows. A chunk job only carries a start id and an end id, never the rows themselves.
  2. Fan out. Every instance of your application picks up chunk jobs and runs them in parallel. Each chunk is one short transaction, so locks are held for seconds. A job is claimed by exactly one worker thread.
  3. Fan in. A follow-up job runs once, after all chunks succeeded. This is where you verify the counts, switch the feature flag or drop the old column.

The state of every chunk is stored in your own SQL database, next to your business data. If a chunk fails halfway, its transaction rolls back and only that chunk is done again. The amount of work you redo after a failure is one chunk, never the whole table.

public void migrateOrders() {
    BackgroundJob
        .startBatch(this::planChunks)
        .continueWith(() -> migrationService.verifyAndSwitchOver());
}

public void planChunks() {
    for (IdRange range : orderRepository.idRangesOf(10_000)) {
        BackgroundJob.enqueue(() -> migrationService.migrate(range.from(), range.to()));
    }
}

@Job(name = "Migrate orders %0 to %1", rateLimiter = "order-migration")
public void migrate(long fromId, long toId) {
    orderRepository.migrateRange(fromId, toId); // one short transaction, safe to run twice
}

Every chunk is a normal job, so each one comes with more than its id range:

  • Retries per chunk. A chunk that throws an exception is retried automatically, 10 times by default, with exponential back-off. You can configure the number of retries.
  • A dashboard that shows what happened. JobRunr ships with a built-in dashboard. It lists every chunk with its state, its attempts and its exceptions. You open the dashboard and see how far along the work is, which chunks failed and why. A chunk that is out of retries stays in the dashboard as failed until someone retries or deletes it from there.
  • Recovery after a crash. If an instance dies, another instance picks up its chunks. Nobody has to find out by hand which ranges were in progress.
  • More speed by adding instances. If you need it done sooner, you start another instance. It claims chunks like the others, without any configuration.

What goes wrong when you build it yourself

Most teams get here in three steps. Each one fixes the previous problem and exposes the next.

Attempt 1 - One long-running SQL statement

UPDATE orders SET details = migrate_details(details);

One transaction for the whole table. It holds its locks until it is done, live traffic queues up behind it, and when the statement timeout hits at 80%, the database rolls all of it back.

Attempt 2 - A loop with a thread pool

So you split the work and run it on a few threads:

ExecutorService pool = Executors.newFixedThreadPool(8);
for (IdRange range : orderRepository.idRangesOf(10_000)) {
    pool.submit(() -> orderRepository.migrateRange(range.from(), range.to()));
}

The transactions are short now. That works until the server restarts halfway. The queue of the thread pool lived in memory, so part of the table is migrated, part is not, and there is no way to tell where it stopped. The other risk is failures… what if one migration thread fails due to an unforeseen data migration exception?

Attempt 3 - Your own progress table

So you record every chunk:

for (MigrationChunk chunk : chunkRepository.findByStatus(PENDING)) {
    pool.submit(() -> {
        orderRepository.migrateRange(chunk.getFromId(), chunk.getToId());
        chunk.setStatus(DONE);
        chunkRepository.save(chunk);
    });
}

A restart now knows where to continue. The list of extras starts to grow:

  • retry logic for the chunk that hit a deadlock
  • a way to spread the work over more than one server without two servers taking the same chunk
  • a way to slow down when the database is busy
  • a way to know that all chunks are done, so the next step can start
  • a screen that shows how far along it is, because someone will ask every hour

Each item is a small project. Together they are a job scheduler that only your team maintains.

What is available in JobRunr?

You needJobRunr OSSJobRunr Pro
Chunk jobs stored in your database, processed on every instanceYesYes
Automatic retries per chunk, with back-offYesYes
Recovery when an instance crashesYesYes
Dashboard with the state and history of every chunkYesYes
Creating many jobs in one go with enqueue(Stream)YesYes
Chunks that only start when planning fully succeeded (batches)NoYes
A follow-up job after all chunks succeeded (continueWith)NoYes
A cap on how many chunks touch the database at once (rate limiters)NoYes
Pause and resume the whole batchNoYes

With OSS you can build the fan out today. The fan in is the part you would have to track yourself.

Questions a sceptical architect asks

Why not a cron script? A script has no memory. When it stops at row 600,000 you find out the next morning, and you restart it by hand. Here every chunk has a state, so a restart continues where it stopped.

Why not Kafka? You can put one message per chunk on a topic. You still need to know when all chunks are done, which ones failed for good, and how to run the next step only then. That bookkeeping is the hard part, and it is what the batch gives you.

Why not let my coding agent build it? It will write the loop and the progress table in an afternoon. You then own the retries, the locking between servers and the edge cases in production for years.

How is this transactional if it is no longer one transaction? It is not one transaction, and that is the point. Each chunk commits on its own. The batch as a whole only succeeds when every chunk succeeded, and the follow-up job waits for that.

How do you make sure no row is missed and no row is migrated twice? The planner splits by id, so every row belongs to exactly one chunk. That split is your code, and it is the part to test. Then make the migration safe to repeat: add a version field to the row and skip rows that already have the new version. A retry of a finished chunk then costs almost nothing.

What if the application writes to a row while it is being migrated? Use optimistic locking on the row. One of the two writers loses. If it is the migration, the chunk retries. If it is the user, they reload and save again.

Can old and new versions of my application run during the migration? Yes, if you plan for it. First add the new fields in a way the old version ignores. Migrate. Remove the old fields in a later deployment, when nothing reads them anymore. This is the hard part of any zero-downtime migration, with or without JobRunr.

How do I know when to step in? The dashboard shows every chunk with its state and its exceptions. With Pro you can also send job traces to your observability platform through OpenTelemetry and alert on failures there.

What does it cost my database? Every chunk is a row in the JobRunr tables and a few small writes. Keep chunks big enough that the real work dominates. A chunk that takes two seconds is a good size. A chunk of one row is not.

Not a fit when

  • The dataset is small. If it succeeds in one transaction, use one transaction.
  • Every row has to change at the same instant. This pattern migrates gradually, so old and new rows exist side by side for a while.
  • A chunk cannot run twice safely. Jobs can be retried, so each chunk has to be idempotent. If your team does not think in jobs, idempotence and re-entrancy yet, read why idempotence matters before you start.

Check the fit for your own system

Paste the URL of this page into your coding agent and ask whether the pattern fits your codebase. Or start with the docs on enqueueing jobs in bulk and batches.

call to action

Try JobRunr yourself, no install required

Walk through 21 hands-on scenarios in our hosted demo and feel how JobRunr handles real-world workflows. Open it in your browser, no setup, no signup.

Launch the interactive demo