Skip to content

feat!: support multiple workers on the same queue - #17441

Merged
AlessioGr merged 6 commits into
mainfrom
fix/job-concurrency
Jul 23, 2026
Merged

AlessioGr merged 6 commits into
mainfrom
fix/job-concurrency

Conversation

@AlessioGr

Copy link
Copy Markdown
Member

This PR prevents two workers on the same queue from claiming and running the same job.

Closes #16043 and #17129

The problem

Two workers can look for work at the same time and find the same available job. The database adapter must ensure that only one worker returns that job as successfully claimed.

The solution

Each worker writes a unique processingToken when it claims jobs. MongoDB and Drizzle use different database operations, so they use the token differently.

MongoDB: find, update, find

MongoDB uses three steps because updateMany does not return the updated documents:

  1. Find candidate jobs.
  2. Update candidates that are still available, setting processing: true and this worker's token.
  3. Find candidates with this worker's token.

The final find now tells us which jobs this worker's update claimed. processing: true could not identify them because every worker writes the same value.

PostgreSQL and SQLite: find, update and return

Drizzle first finds candidates, then runs one conditional UPDATE ... RETURNING statement. The update only changes jobs that are still processing: false and directly returns the IDs it changed.

If two workers found the same job, only one update can change it from processing: false to true. The other update does not return that job, so only the winner runs it.

For this specific race, Drizzle does not need the processingToken to identify the winner because the update already returns the winning IDs. The token is mainly needed by MongoDB's final find and is stored consistently by every adapter.

FOR UPDATE SKIP LOCKED is not needed to prevent duplicate claims. It could reduce waiting under heavy contention, but would add PostgreSQL-specific code.

Payload clears processingToken when a job stops processing.

What this does not fix

This PR does not add leases or crash recovery. A crashed worker can still leave processing: true behind; the follow-up PR will address that.

How this helps crash recovery later

The token also gives Payload a clear way to identify which worker currently owns a job. In the follow-up crash-recovery PR, a replacement worker can claim an abandoned job with a new token. Updates from the old worker can then be rejected because its token no longer matches.

This PR does not add that recovery behavior yet, but processingToken gives it a safe ownership check to build on.

=> efficient MongoDB queries are not the only reason we're adding this new processingToken field.

Breaking change for custom adapters

This adds the nullable processingToken field to payload-jobs, so existing SQL databases need a migration that adds the corresponding column. That migration will be added in a separate PR. MongoDB does not require a data migration.

updateJobs is now required when calling createDatabaseAdapter. The old fallback could not guarantee an atomic claim because it selected jobs before updating them by ID. Custom adapters must ensure that a claim only updates jobs that are still not processing. When a processingToken is provided, it must return only the jobs claimed by that runner.

Testing

Added a regression test that simulates two workers polling the same queue and verifies that only one can claim the job. It passes on MongoDB, SQLite, and PostgreSQL. It consistently fails before this PR.

@AlessioGr
AlessioGr enabled auto-merge (squash) July 22, 2026 02:25
@AlessioGr AlessioGr changed the title feat!: support running multiple workers on the same queue feat!: support multiple workers on the same queue Jul 22, 2026
@AlessioGr
AlessioGr disabled auto-merge July 22, 2026 02:25
@AlessioGr
AlessioGr enabled auto-merge (squash) July 22, 2026 02:25
}
const claimedJobsQuery = {
_id: { $in: candidateIDs },
processingToken: { $eq: data.processingToken },

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is why mongo needs processingToken. Model.updateMany does not return the jobs it updated. So without processingToken, the following Model.find could be finding jobs updated by a different worker, causing 2 workers running the same jobs

@github-actions

Copy link
Copy Markdown
Contributor

📦 esbuild Bundle Analysis for payload

This analysis was generated by esbuild-bundle-analyzer. 🤖

Meta File Out File Size (raw) Note
packages/next/meta_index.json esbuild/index.js 201.89 KB 🆕 Added
packages/payload/meta_index.json esbuild/index.js 1.41 MB 🆕 Added
packages/payload/meta_shared.json esbuild/exports/shared.js 213.20 KB 🆕 Added
packages/richtext-lexical/meta_client.json esbuild/exports/client_optimized/index.js 285.56 KB 🆕 Added
packages/ui/meta_client.json esbuild/exports/client_optimized/index.js 36.16 KB 🆕 Added
packages/ui/meta_shared.json esbuild/exports/shared_optimized/index.js 18.95 KB 🆕 Added
Largest paths These visualization shows top 20 largest paths in the bundle.

Meta file: packages/next/meta_index.json, Out file: esbuild/index.js

Path Size
../../node_modules ${{\color{Goldenrod}{ ████████████████████████▋ }}}$ 98.9%, 197.86 KB
dist/adapters/router.js ${{\color{Goldenrod}{ }}}$ 0.4%, 718 B
dist/adapters/server.js ${{\color{Goldenrod}{ }}}$ 0.3%, 533 B
dist/adapters/layout.js ${{\color{Goldenrod}{ }}}$ 0.3%, 526 B
dist/adapters/views.js ${{\color{Goldenrod}{ }}}$ 0.2%, 409 B
dist/esbuildEntry.js ${{\color{Goldenrod}{ }}}$ 0.0%, 0 B

Meta file: packages/payload/meta_index.json, Out file: esbuild/index.js

Path Size
../../node_modules ${{\color{Goldenrod}{ █████████████████▏ }}}$ 68.8%, 964.37 KB
dist/fields/hooks ${{\color{Goldenrod}{ ▊ }}}$ 3.2%, 44.37 KB
dist/collections/operations ${{\color{Goldenrod}{ ▊ }}}$ 3.0%, 42.69 KB
dist/utilities/configToJSONSchema.js ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 15.99 KB
dist/auth/operations ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 15.68 KB
dist/fields/config ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 13.79 KB
dist/globals/operations ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 13.36 KB
dist/queues/operations ${{\color{Goldenrod}{ ▏ }}}$ 0.9%, 12.76 KB
dist/fields/validations.js ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 10.73 KB
dist/bin/generateImportMap ${{\color{Goldenrod}{ ▏ }}}$ 0.7%, 9.84 KB
dist/collections/config ${{\color{Goldenrod}{ ▏ }}}$ 0.7%, 9.30 KB
dist/config/orderable ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 8.07 KB
dist/index.js ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 7.96 KB
dist/uploads/fetchAPI-multipart ${{\color{Goldenrod}{ ▏ }}}$ 0.6%, 7.84 KB
dist/hierarchy/utils ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 7.64 KB
dist/database/migrations ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 7.55 KB
dist/config/sanitize.js ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 6.98 KB
dist/collections/endpoints ${{\color{Goldenrod}{ }}}$ 0.4%, 6.12 KB
dist/queues/config ${{\color{Goldenrod}{ }}}$ 0.4%, 5.68 KB
dist/uploads/endpoints ${{\color{Goldenrod}{ }}}$ 0.4%, 5.56 KB
(other) ${{\color{Goldenrod}{ ███████▊ }}}$ 31.2%, 437.47 KB

Meta file: packages/payload/meta_shared.json, Out file: esbuild/exports/shared.js

Path Size
../../node_modules ${{\color{Goldenrod}{ █████████████████▉ }}}$ 71.9%, 150.13 KB
dist/fields/validations.js ${{\color{Goldenrod}{ █▎ }}}$ 5.1%, 10.73 KB
dist/fields/config ${{\color{Goldenrod}{ ▋ }}}$ 2.8%, 5.82 KB
dist/utilities/traverseFields.js ${{\color{Goldenrod}{ ▌ }}}$ 2.1%, 4.44 KB
dist/collections/config ${{\color{Goldenrod}{ ▍ }}}$ 1.6%, 3.32 KB
dist/config/orderable ${{\color{Goldenrod}{ ▍ }}}$ 1.5%, 3.13 KB
dist/fields/baseFields ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 2.79 KB
dist/utilities/deepCopyObject.js ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 2.69 KB
dist/config/client.js ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 2.68 KB
dist/auth/cookies.js ${{\color{Goldenrod}{ ▏ }}}$ 0.7%, 1.55 KB
dist/utilities/flattenTopLevelFields.js ${{\color{Goldenrod}{ ▏ }}}$ 0.7%, 1.41 KB
dist/utilities/getVersionsConfig.js ${{\color{Goldenrod}{ ▏ }}}$ 0.5%, 1.04 KB
dist/globals/config ${{\color{Goldenrod}{ }}}$ 0.4%, 939 B
dist/utilities/flattenAllFields.js ${{\color{Goldenrod}{ }}}$ 0.4%, 793 B
dist/utilities/unflatten.js ${{\color{Goldenrod}{ }}}$ 0.4%, 779 B
dist/utilities/sanitizeUserDataForEmail.js ${{\color{Goldenrod}{ }}}$ 0.3%, 713 B
dist/auth/extractJWT.js ${{\color{Goldenrod}{ }}}$ 0.3%, 696 B
dist/utilities/getFieldPermissions.js ${{\color{Goldenrod}{ }}}$ 0.3%, 651 B
dist/errors/ValidationError.js ${{\color{Goldenrod}{ }}}$ 0.3%, 577 B
dist/bin/generateImportMap ${{\color{Goldenrod}{ }}}$ 0.3%, 561 B
(other) ${{\color{Goldenrod}{ ███████ }}}$ 28.1%, 58.59 KB

Meta file: packages/richtext-lexical/meta_client.json, Out file: esbuild/exports/client_optimized/index.js

Path Size
dist/features/blocks ${{\color{Goldenrod}{ ███▎ }}}$ 13.2%, 37.20 KB
dist/lexical/ui ${{\color{Goldenrod}{ ███ }}}$ 12.1%, 34.16 KB
dist/lexical/plugins ${{\color{Goldenrod}{ ██▉ }}}$ 11.8%, 33.18 KB
dist/features/experimental_table ${{\color{Goldenrod}{ ██▍ }}}$ 9.6%, 27.22 KB
dist/features/link ${{\color{Goldenrod}{ █▋ }}}$ 6.7%, 18.82 KB
dist/features/toolbars ${{\color{Goldenrod}{ █▍ }}}$ 5.9%, 16.58 KB
dist/features/upload ${{\color{Goldenrod}{ █▎ }}}$ 5.0%, 14.09 KB
dist/features/textState ${{\color{Goldenrod}{ ▉ }}}$ 3.9%, 11.08 KB
dist/lexical/utils ${{\color{Goldenrod}{ ▉ }}}$ 3.5%, 10.02 KB
dist/features/relationship ${{\color{Goldenrod}{ ▊ }}}$ 3.4%, 9.61 KB
dist/features/converters ${{\color{Goldenrod}{ ▊ }}}$ 3.0%, 8.36 KB
dist/utilities/fieldsDrawer ${{\color{Goldenrod}{ ▋ }}}$ 2.9%, 8.12 KB
dist/features/debug ${{\color{Goldenrod}{ ▋ }}}$ 2.6%, 7.40 KB
dist/lexical/config ${{\color{Goldenrod}{ ▍ }}}$ 1.8%, 5.14 KB
dist/features/lists ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 3.64 KB
dist/features/format ${{\color{Goldenrod}{ ▎ }}}$ 1.2%, 3.28 KB
dist/lexical/LexicalEditor.js ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 3.23 KB
dist/features/horizontalRule ${{\color{Goldenrod}{ ▎ }}}$ 1.1%, 3.18 KB
dist/field/Field.js ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 2.88 KB
dist/lexical/nodes ${{\color{Goldenrod}{ ▏ }}}$ 0.9%, 2.66 KB
(other) ${{\color{Goldenrod}{ █████████████████████▋ }}}$ 86.8%, 245.15 KB

Meta file: packages/ui/meta_client.json, Out file: esbuild/exports/client_optimized/index.js

Path Size
dist/exports/client ${{\color{Goldenrod}{ █████████████████████████ }}}$ 100.0%, 26.63 KB

Meta file: packages/ui/meta_shared.json, Out file: esbuild/exports/shared_optimized/index.js

Path Size
dist/graphics/Logo ${{\color{Goldenrod}{ ███████▋ }}}$ 30.5%, 5.57 KB
../../node_modules ${{\color{Goldenrod}{ ███▌ }}}$ 14.5%, 2.65 KB
dist/graphics/Icon ${{\color{Goldenrod}{ ██ }}}$ 8.3%, 1.51 KB
dist/utilities/formatDocTitle ${{\color{Goldenrod}{ █▊ }}}$ 7.2%, 1.32 KB
dist/providers/TableColumns ${{\color{Goldenrod}{ █▏ }}}$ 4.7%, 866 B
dist/utilities/getGlobalData.js ${{\color{Goldenrod}{ █ }}}$ 4.2%, 762 B
dist/utilities/api.js ${{\color{Goldenrod}{ █ }}}$ 4.1%, 756 B
dist/utilities/groupNavItems.js ${{\color{Goldenrod}{ █ }}}$ 4.1%, 745 B
dist/elements/Translation ${{\color{Goldenrod}{ ▋ }}}$ 2.7%, 493 B
dist/utilities/handleTakeOver.js ${{\color{Goldenrod}{ ▌ }}}$ 2.4%, 440 B
dist/utilities/traverseForLocalizedFields.js ${{\color{Goldenrod}{ ▌ }}}$ 2.3%, 419 B
dist/elements/withMergedProps ${{\color{Goldenrod}{ ▍ }}}$ 1.9%, 339 B
dist/utilities/getNavGroups.js ${{\color{Goldenrod}{ ▍ }}}$ 1.9%, 338 B
dist/utilities/getVisibleEntities.js ${{\color{Goldenrod}{ ▍ }}}$ 1.8%, 329 B
dist/elements/WithServerSideProps ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 232 B
dist/layouts/Root ${{\color{Goldenrod}{ ▎ }}}$ 1.3%, 230 B
dist/utilities/handleGoBack.js ${{\color{Goldenrod}{ ▎ }}}$ 1.0%, 180 B
dist/fields/mergeFieldStyles.js ${{\color{Goldenrod}{ ▏ }}}$ 0.9%, 158 B
dist/forms/Form ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 152 B
dist/utilities/handleBackToDashboard.js ${{\color{Goldenrod}{ ▏ }}}$ 0.8%, 152 B
(other) ${{\color{Goldenrod}{ █████████████████▍ }}}$ 69.5%, 12.68 KB
Details

Next to the size is how much the size has increased or decreased compared with the base branch of this PR.

  • ‼️: Size increased by 20% or more. Special attention should be given to this.
  • ⚠️: Size increased in acceptable range (lower than 20%).
  • ✅: No change or even downsized.
  • 🗑️: The out file is deleted: not found in base branch.
  • 🆕: The out file is newly found: will be added to base branch.


const db = getPrimaryDb(this, await getTransaction(this, req))

if (isInitialJobClaim(data)) {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default path: sequentially call upsertRow for each job. This obviously won't work for us here. We need to perform one atomic compare-and-set operation


import { jobsCollectionSlug } from '../queues/config/collection.js'

export const defaultUpdateJobs: UpdateJobs = async function updateMany(

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All our own db adapters already provide an updateJobs method. No point making it optional and providing an unreliably defaultUpdateJobs function we need to maintain.

Comment thread test/queues/int.spec.ts
},
},
})
expect(createdDocuments.totalDocs).toBe(1)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Before this PR, this almost consistently returns 10 instead of 1. So this should be a pretty reliable test

// Only one job to run
const job = await updateJob({
id,
const updatedDocs = await updateJobs({

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously, the updateJob call did not check that processing was still false as it did not provide a where. Now, we need this check to benefit from the concurrency protection implemented by the database adapters.

remainingJobsFromQueried: 0,
})
expect(consoleCount).toHaveBeenCalledTimes(15) // Should be 15 sql calls if the optimizations are used. If not, this would be 23 calls
expect(consoleCount).toHaveBeenCalledTimes(14) // Should be 14 sql calls if the optimizations are used. If not, this would be 23 calls

@AlessioGr AlessioGr Jul 22, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Job queue is now less chatty! Yay! People who host database and Payload in different regions will be happy

if (documentsToUpdate.length === 0) {
} else if (limit === 1) {
/**
* Select, update, and return one job atomically in a single database call.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perf optimization. The else if (typeof limit === 'number' && limit > 1) { branch would be enough, but we can do it in a single db round-trip if we're only modifying one document

@DanRibbens DanRibbens left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we may need the same pattern on migrations, since this can also happen today.

@AlessioGr
AlessioGr merged commit 7ae0cda into main Jul 23, 2026
669 of 680 checks passed
@AlessioGr
AlessioGr deleted the fix/job-concurrency branch July 23, 2026 18:36
AlessioGr added a commit that referenced this pull request Jul 26, 2026
This PR lets Payload recover Jobs Queue jobs after a worker crashes. It
replaces the permanent `processing` flag with a renewable
`processingUntil` lease and builds on
[#17441](#17441), which makes
the initial job claim safe when multiple workers poll the same queue.

## Why

Previously, a worker set `processing: true` when it claimed a job. If
that process crashed, nothing reset the flag, so Payload treated the job
as running forever.

For example, a schedule runs every 10 minutes but does not queue a new
job while the previous one is processing. If its worker crashes, the old
job stays at `processing: true`, cannot be picked up again, and can
block every future scheduled run.

## How it works

A job is claimable when `processingUntil` is missing or expired.
Claiming it atomically writes:

- `processingUntil`: how long Payload should consider the worker active
- `processingToken`: which worker attempt currently owns the job

While the job runs, a heartbeat renews `processingUntil` every third of
the lease duration. A healthy job can therefore run longer than one
lease; this is not a task timeout.

Worker-owned updates - including heartbeats, task logs, completion, and
handled errors - must still match the worker's token and have enough
lease time remaining. If an update no longer matches, Payload throws an
internal `JobRunAbortedError` and stops accepting results from that
worker. This prevents a timed-out worker from overwriting a newer
attempt.

When a worker disappears, its heartbeat stops. After the lease expires,
the next normal `payload.jobs.run()` or `runByID()` call can claim the
job directly with a new token and lease. No separate cleanup step is
required.

A crash intentionally does not increment `totalTried` or consume the
handler's retry configuration. Completed task logs are kept, so recovery
continues from the remaining tasks.

## Configuration

The default lease is 20 minutes and the default safety buffer is 30
seconds:

```ts
jobs: {
  processingLease: {
    duration: 20 * 60 * 1000,
    safetyBuffer: 30 * 1000,
  },
}
```

`duration` controls how long a job remains owned without a successful
heartbeat, and will delay recovery. 20 minutes was chosen as the
default, because recovery usually is rare and not time-sensitive.

`safetyBuffer` is the minimum time that must remain before a worker
starts a job update. It gives db adapters that read and write separately
time to finish before the lease expires. It should be longer than a
normal database update and shorter than the lease duration.

## Why the token and safety buffer are both needed

[#17441](#17441) protects
claim time: only one worker can change a pending job into a claimed job.

This PR must also protect later writes. After a lease expires, Worker B
can recover a job while Worker A is still finishing old work.
`processingUntil` alone only says that some worker has an active lease.
The stable `processingToken` identifies whether the update belongs to
Worker A or Worker B.

Some db adapters first find a matching job and then write it. Without a
safety window, this race is possible:

1. Worker A verifies its token just before its lease expires.
2. The lease expires before A's job update write finishes.
3. Worker B claims the job with a new token.
4. A's delayed write could overwrite B's state.

The safety buffer prevents A from starting that update near lease
expiry. This is a cross-db-adapter safety margin, not an atomic database
guarantee. It can be increased for slower remote adapters, if you expect
an update to take longer than 30 seconds.

MongoDB applies the ownership query and update atomically with
`findOneAndUpdate()` or `updateMany()`, so it does not rely on the
buffer for correctness. The buffer can be set to `0` for a db adapter
like mongodb with the same guarantee.

## Breaking change

The `processing` field on `payload-jobs` is replaced by the nullable,
indexed `processingUntil` date. Custom collection overrides and direct
database queries that use `processing` must be updated.

Existing SQL databases need a migration that replaces this column.
Migration files will be added in a separate PR; MongoDB does not require
a schema migration.

---

- To see the specific tasks where the Asana app for GitHub is being
used, see below:
  - https://app.asana.com/0/0/1216353649387086
@tiendungnguyen24

Copy link
Copy Markdown

Hi! We run Payload 3.x jobs with more than one runner on the same queue and hit the non-atomic claim this PR fixes (the same job ran on two hosts). Two questions:

  1. Is a backport to 3.x possible, at least the findOneAndUpdate claim for limit: 1?
  2. Is there a rough timeline for a stable 4.0?

Thanks!

JessRynkar added a commit that referenced this pull request Nov 16, 2026
#18709)

### Summary of Changes
- **`@payloadcms/db-mongodb` (`updateJobs.ts`):**
- Implement atomic single-job claiming via
`Model.findOneAndUpdate(query, updateData, ...)` for `limit === 1`.
- Preserve the original `query` (`processing: false`) in `$and: [query,
{ _id: { $in: candidateIDs } }]` during batch claiming (`limit > 1`) so
concurrent workers do not overwrite each other's claims.
- **`@payloadcms/drizzle` (`updateJobs.ts`):**
- Perform single-pass atomic row claiming guarded by
`and(inArray(table.id, jobIDs), eq(table.processing, false))` returning
only newly claimed rows when `isInitialJobClaim(data)`.

### Root Cause / Technical Context
In Payload 3.x (`v3.90.2`), job claiming uses a non-atomic two-phase
`find` followed by `updateMany` per row without concurrency guards:
1. Two or more workers polling simultaneously find the same pending jobs
with `processing: false`.
2. Both workers mark and execute the same jobs concurrently.
3. With `deleteJobOnComplete: true`, the faster runner finishes and
deletes the job row. The slower runner then attempts to update the
deleted row, resulting in `TypeError: Cannot read properties of null
(reading 'log')` and HTTP 500 errors.

### Verification & Testing
- Backported the core non-breaking claiming logic from #17441 into the
3.x branch without requiring schema changes or database migrations.
- Tested single-runner (`limit: 1`) atomic `findOneAndUpdate` and
multi-runner candidate filtering.

Closes #18565

---------

Co-authored-by: Sasha Rakhmatulin <[email protected]>
Co-authored-by: Jessica Rynkar <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Race condition in defaultUpdateJobs prevents safe multi-worker job processing

3 participants