From 58769d2f85068b0d8af6a1fcfbca665fb941f792 Mon Sep 17 00:00:00 2001 From: EfeDurmaz16 Date: Wed, 2 Dec 2026 00:07:24 +0300 Subject: [PATCH] Spread database queue workers across candidate jobs Workers racing for a database queue all read the same five oldest jobs and tried them in the same order, so most claims lost to another worker. A worker still tries the oldest job first, which keeps a lone worker in dispatch order, and then starts at a random one of the others. The claim itself is unchanged. --- Cargo.lock | 1 + crates/queue/Cargo.toml | 1 + crates/queue/src/queue/database.rs | 14 +++++++++++--- tests/queue_worker.rs | 17 +++++++++++++++++ 4 files changed, 30 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 497a249b3..f89140477 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2920,6 +2920,7 @@ dependencies = [ "clap", "comfy-table", "futures-util", + "getrandom 0.4.3", "hex", "hmac", "inventory", diff --git a/crates/queue/Cargo.toml b/crates/queue/Cargo.toml index 71e7e3c3a..399be11a7 100644 --- a/crates/queue/Cargo.toml +++ b/crates/queue/Cargo.toml @@ -41,6 +41,7 @@ aws-smithy-http-client = { workspace = true, optional = true } clap.workspace = true comfy-table.workspace = true futures-util.workspace = true +getrandom.workspace = true inventory.workspace = true jiff.workspace = true laravel-rust-queue-macros.workspace = true diff --git a/crates/queue/src/queue/database.rs b/crates/queue/src/queue/database.rs index e80b044b9..4ed2a909d 100644 --- a/crates/queue/src/queue/database.rs +++ b/crates/queue/src/queue/database.rs @@ -123,6 +123,13 @@ fn later(now: Timestamp, delay: Duration) -> Timestamp { now.checked_add(delay).unwrap_or(Timestamp::MAX) } +/// Where a worker starts among the `count` candidates after the oldest one. Workers that lose the oldest job to +/// another worker then try different jobs instead of all trying the next one. +fn start(count: usize) -> usize { + let random = usize::try_from(getrandom::u32().unwrap_or_default()).unwrap_or_default(); + random.checked_rem(count).unwrap_or_default() +} + #[derive(Clone)] struct Table(Builder); @@ -136,7 +143,7 @@ impl Table { async fn reserve(&self, queue: &str) -> Result> { loop { let now = system_timestamp(); - let candidates: Vec<(i64, i64)> = self + let mut candidates: Vec<(i64, i64)> = self .0 .clone() .select(["id", "attempts"]) @@ -146,9 +153,10 @@ impl Table { .use_write_connection() .get() .await?; - if candidates.is_empty() { + let Some((_, rest)) = candidates.split_first_mut() else { return Ok(None); - } + }; + rest.rotate_left(start(rest.len())); for (id, attempts) in candidates { if let Some(reserved) = self.claim(id, attempts, now).await? { diff --git a/tests/queue_worker.rs b/tests/queue_worker.rs index 1f38d9d5f..b35fc6324 100644 --- a/tests/queue_worker.rs +++ b/tests/queue_worker.rs @@ -597,6 +597,22 @@ async fn sqlite_workers_retry_fail_and_recover_jobs() { worker_contract(&app).await; } +#[cfg(any(feature = "database-postgres", feature = "database-mysql"))] +async fn racing_workers_contract(app: &Application) { + for note in 0..40 { + dispatch(app, Note(format!("note {note:02}"))).await; + } + + let (first, second, third) = tokio::join!(work(app, ""), work(app, ""), work(app, "")); + first.assert_successful(); + second.assert_successful(); + third.assert_successful(); + let mut notes = records(app).await; + notes.sort(); + assert_eq!(notes, (0..40).map(|note| format!("note {note:02}")).collect::>()); + assert!(rows(app).await.is_empty()); +} + #[cfg(feature = "database-postgres")] #[tokio::test] #[ignore = "requires LARAVEL_TEST_POSTGRES_URL pointing to a disposable database"] @@ -622,6 +638,7 @@ async fn database_contracts(url: String) { let app = application(url.clone()).await; sizes_contract(&app).await; worker_contract(&app).await; + racing_workers_contract(&application(url.clone()).await).await; #[cfg(feature = "database-sqlite")] crate::queue_batches::concurrent_completion_contract(&crate::queue_batches::application(url, "database").await) .await;