Repository navigation
feat!: support multiple workers on the same queue - #17441
Conversation
| } | ||
| const claimedJobsQuery = { | ||
| _id: { $in: candidateIDs }, | ||
| processingToken: { $eq: data.processingToken }, |
There was a problem hiding this comment.
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
📦 esbuild Bundle Analysis for payloadThis analysis was generated by esbuild-bundle-analyzer. 🤖
Largest pathsThese visualization shows top 20 largest paths in the bundle.Meta file: packages/next/meta_index.json, Out file: esbuild/index.js
Meta file: packages/payload/meta_index.json, Out file: esbuild/index.js
Meta file: packages/payload/meta_shared.json, Out file: esbuild/exports/shared.js
Meta file: packages/richtext-lexical/meta_client.json, Out file: esbuild/exports/client_optimized/index.js
Meta file: packages/ui/meta_client.json, Out file: esbuild/exports/client_optimized/index.js
Meta file: packages/ui/meta_shared.json, Out file: esbuild/exports/shared_optimized/index.js
DetailsNext to the size is how much the size has increased or decreased compared with the base branch of this PR.
|
|
|
||
| const db = getPrimaryDb(this, await getTransaction(this, req)) | ||
|
|
||
| if (isInitialJobClaim(data)) { |
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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.
| }, | ||
| }, | ||
| }) | ||
| expect(createdDocuments.totalDocs).toBe(1) |
There was a problem hiding this comment.
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({ |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
I think we may need the same pattern on migrations, since this can also happen today.
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
|
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:
Thanks! |
#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]>
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
processingTokenwhen 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
updateManydoes not return the updated documents:processing: trueand this worker's token.The final find now tells us which jobs this worker's update claimed.
processing: truecould 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 ... RETURNINGstatement. The update only changes jobs that are stillprocessing: falseand directly returns the IDs it changed.If two workers found the same job, only one update can change it from
processing: falsetotrue. The other update does not return that job, so only the winner runs it.For this specific race, Drizzle does not need the
processingTokento 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 LOCKEDis not needed to prevent duplicate claims. It could reduce waiting under heavy contention, but would add PostgreSQL-specific code.Payload clears
processingTokenwhen 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: truebehind; 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
processingTokengives it a safe ownership check to build on.=> efficient MongoDB queries are not the only reason we're adding this new
processingTokenfield.Breaking change for custom adapters
This adds the nullable
processingTokenfield topayload-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.updateJobsis now required when callingcreateDatabaseAdapter. 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 aprocessingTokenis 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.