Menu

Post image 1
Post image 2
1 / 2
0

Set-Based Updates in Rails: 4 Hours to 8 Seconds

DEV Community·Wilbur Suero·21 days ago
#UC3hlt5o
#comment#rails#sql#user#fullscreen#update_all
Reading 0:00
15s threshold

I once inherited a background job to deactivate stale users. In production, a job processing 50,000 users that should have taken a minute was taking over 4 hours, consuming 2GB of RAM, and frequently timing out. The culprit was a classic Rails performance pitfall: the N+1 update loop. The code looked innocent: # Find users whose last login was more than 90 days ago users_to_deactivate = User . where ( "last_login_at < ?" , 90 . days . ago ) users_to_deactivate . each do | user | # This runs one UPDATE query for every single user user . update ( active: false ) end Enter fullscreen mode Exit fullscreen mode This generates a flood of queries, hammering the database with thousands of individual transactions: -- The N+1 Update Hell SELECT "users" . * FROM "users" WHERE ( last_login_at < '2025-11-30...' ); UPDATE "users" SET "active" = false , "updated_at" = '...' WHERE "users" . "id" = 1 ; UPDATE "users" SET "active" = false , "updated_at" = '...' WHERE "users" . "id" = 2 ; -- ...…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More