Skip to content

Commit bd85b55

Browse files
authored
Merge pull request #23 from netlogix/fix/claim-does-not-use-its-dedicated-index-properly
fix: optimize claiming query to use idx_for_update index
2 parents 6d28561 + 38bbb34 commit bd85b55

1 file changed

Lines changed: 25 additions & 8 deletions

File tree

Classes/Domain/Scheduler.php

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -81,15 +81,32 @@ public function next(string $groupName): ?ScheduledJob
8181
$this->validateGroupName($groupName);
8282
$claim = Algorithms::generateUUID();
8383

84-
$update = /** @lang MySQL */
85-
'
86-
UPDATE ' . ScheduledJob::TABLE_NAME . '
84+
$update =
85+
/**
86+
* Step 1: Create a derived table using the "idx_for_update" index
87+
* that only contains one row.
88+
* Step 2: Join that row against the actual job to be claimed on
89+
* the primary key column.
90+
* Step 3: UPDATE that row with the claim value.
91+
*
92+
* Otherwise, MySQL would use the "idx_groupname" index, fetch
93+
* millions of rows, use a temp table to sort those millions
94+
* and limit the result to the one row to be claimed.
95+
*
96+
* @lang MySQL
97+
*/
98+
'
99+
UPDATE (SELECT identifier
100+
FROM ' . ScheduledJob::TABLE_NAME . '
101+
WHERE duedate <= :now
102+
AND groupname = :groupname
103+
AND claimed = ""
104+
ORDER BY duedate ASC
105+
LIMIT 1) AS delinquents
106+
INNER JOIN ' . ScheduledJob::TABLE_NAME . '
107+
USING (identifier)
87108
SET claimed = :claimed
88-
WHERE duedate <= :now
89-
AND groupname = :groupname
90-
AND claimed = ""
91-
ORDER BY duedate ASC
92-
LIMIT 1
109+
WHERE claimed = ""
93110
';
94111
$this->dbal
95112
->executeQuery(

0 commit comments

Comments
 (0)