From 6a915d6f2d462a376d8cecc062dd58e520339b5e Mon Sep 17 00:00:00 2001 From: Toon Claes Date: Tue, 2 May 2017 22:52:14 +0200 Subject: Limit `update_tracked_fields` to write to database once/hour Every time a user logs in or out, the Trackable attributes are written to the database. This is causing a lot of load on the database, for data that isn't really critical. So to avoid the database being hammered, add a Gitlab::ExclusiveLease before writing trackable attributes to the database. This lease expires after an hour, so only when the attributes were written more than an hour ago, they can be written again. Otherwise they are ignored. --- app/models/user.rb | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'app/models') diff --git a/app/models/user.rb b/app/models/user.rb index accaa91b805..05f636c020a 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -40,6 +40,16 @@ class User < ActiveRecord::Base devise :lockable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :confirmable, :registerable + # Limit trackable fields to update at most once every hour + alias_method :devise_update_tracked_fields!, :update_tracked_fields! + + def update_tracked_fields!(request) + lease = Gitlab::ExclusiveLease.new("user_update_tracked_fields:#{id}", timeout: 1.hour.to_i) + return unless lease.try_obtain + + devise_update_tracked_fields!(request) + end + attr_accessor :force_random_password # Virtual attribute for authenticating by either username or email -- cgit v1.2.1 From 3531ea096f730b8533df259ac2f6cbed738965ed Mon Sep 17 00:00:00 2001 From: Toon Claes Date: Fri, 5 May 2017 09:29:03 +0200 Subject: Devise can assign trackable fields, but only allow writes once/hour Not assigning the trackable fields seems to cause strange side-effects. --- app/models/user.rb | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'app/models') diff --git a/app/models/user.rb b/app/models/user.rb index 05f636c020a..0b358fd4b19 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -40,14 +40,15 @@ class User < ActiveRecord::Base devise :lockable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :confirmable, :registerable - # Limit trackable fields to update at most once every hour - alias_method :devise_update_tracked_fields!, :update_tracked_fields! - + # Override Devise::Models::Trackable#update_tracked_fields! + # to limit database writes to at most once every hour def update_tracked_fields!(request) + update_tracked_fields(request) + lease = Gitlab::ExclusiveLease.new("user_update_tracked_fields:#{id}", timeout: 1.hour.to_i) return unless lease.try_obtain - devise_update_tracked_fields!(request) + save(validate: false) end attr_accessor :force_random_password -- cgit v1.2.1