Skip to content

Commit 07f1dae

Browse files
author
Черненков Алексей Юрьевич
committed
Merge branch 'fix/DEX-2876/optimize-min-query' into 'master'
[DEX-2876] Optimize 'MIN(created_at)' query Closes DEX-2876 See merge request nstmrt/rubygems/outbox!118
2 parents e7459a3 + 16c8bd8 commit 07f1dae

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
1313

1414
### Fixed
1515

16+
## [6.19.1] - 2025-02-20
17+
18+
### Fixed
19+
20+
- `MIN(created_at)` query in stale items deletion job has been optimised
21+
1622
## [6.19.0] - 2025-02-11
1723

1824
### Added

app/jobs/sbmt/outbox/base_delete_stale_items_job.rb

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,10 @@ def delete_items_in_batches_with_between(waterline, statuses)
118118
batch_size = item_class.config.deletion_batch_size
119119
time_window = item_class.config.deletion_time_window
120120
min_date = Outbox.database_switcher.use_slave do
121-
item_class.where(table[:status].in(statuses)).minimum(:created_at)
121+
# This query assumes that record with minimum 'id' also has minimum 'created_at'.
122+
# We use it because it should be faster than plain 'SELECT MIN(created_at) ...'.
123+
min_id = item_class.select(table[:id].minimum).where(status: statuses)
124+
item_class.select(:created_at).where(table[:id].eq(min_id.arel)).first&.created_at
122125
end
123126
deleted_count = nil
124127

@@ -174,10 +177,14 @@ def mysql_delete_in_batches(waterline_failed, waterline_delivered)
174177
end
175178

176179
def delete_items_in_batches_with_between_mysql(waterline, statuses)
180+
table = item_class.arel_table
177181
batch_size = item_class.config.deletion_batch_size
178182
time_window = item_class.config.deletion_time_window
179183
min_date = Outbox.database_switcher.use_slave do
180-
item_class.where(status: statuses).minimum(:created_at)
184+
# This query assumes that record with minimum 'id' also has minimum 'created_at'.
185+
# We use it because plain 'SELECT MIN(created_at) ...' is VERY slow in MySQL.
186+
min_id = item_class.select(table[:id].minimum).where(status: statuses)
187+
item_class.select(:created_at).where(table[:id].eq(min_id.arel)).first&.created_at
181188
end
182189
deleted_count = nil
183190

lib/sbmt/outbox/version.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22

33
module Sbmt
44
module Outbox
5-
VERSION = "6.19.0"
5+
VERSION = "6.19.1"
66
end
77
end

0 commit comments

Comments
 (0)