FIX: concurrency bug when creating topic thumbnails

FIX: concurrency bug when creating topic thumbnails

We were failing erratically when backfilling topic thumbnails.

This ensures that racing threads/processes will not conflict.

diff --git a/app/models/topic_thumbnail.rb b/app/models/topic_thumbnail.rb
index 139ddde..ae8d17b 100644
--- a/app/models/topic_thumbnail.rb
+++ b/app/models/topic_thumbnail.rb
@@ -21,7 +21,19 @@ class TopicThumbnail < ActiveRecord::Base
       optimized = OptimizedImage.create_for(original, target_width, target_height)
     end
 
-    create!(upload: original, max_width: max_width, max_height: max_height, optimized_image: optimized)
+    # may have been associated already, bulk insert will skip dupes
+    TopicThumbnail.insert_all([
+      upload_id: original.id,
+      max_width: max_width,
+      max_height: max_height,
+      optimized_image_id: optimized.id
+    ])
+
+    TopicThumbnail.find_by(
+      upload: original,
+      max_width: max_width,
+      max_height: max_height
+    )
   end
 
   def self.ensure_consistency!

GitHub sha: 337bd9a0

1 Like