Skip to content

Commit 440f173

Browse files
ClearlyClaireGargron
authored andcommitted
Avoid race conditions when creating backups (mastodon#10234)
Under load, multiple backups for a single user could be planned, which is very expensive.
1 parent 7d0076d commit 440f173

1 file changed

Lines changed: 16 additions & 2 deletions

File tree

app/controllers/settings/exports_controller.rb

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,25 @@ def show
1313
end
1414

1515
def create
16-
authorize :backup, :create?
16+
raise Mastodon::NotPermittedError unless user_signed_in?
17+
18+
backup = nil
19+
20+
RedisLock.acquire(lock_options) do |lock|
21+
if lock.acquired?
22+
authorize :backup, :create?
23+
backup = current_user.backups.create!
24+
else
25+
raise Mastodon::RaceConditionError
26+
end
27+
end
1728

18-
backup = current_user.backups.create!
1929
BackupWorker.perform_async(backup.id)
2030

2131
redirect_to settings_export_path
2232
end
33+
34+
def lock_options
35+
{ redis: Redis.current, key: "backup:#{current_user.id}" }
36+
end
2337
end

0 commit comments

Comments
 (0)