ruby-on-railsrubygrape-apigrape-entity

Rails Grape api: performannce when getting more data


i'm facing performance issue using grape api. i have following models:

class Profile
   has_many :transitive_user_profiles
end

class TransitiveUserProfile < ApplicationRecord
  belongs_to :profile
  belongs_to :user
  belongs_to :client

end

class DefaultAddress 
  belongs_to :user
end

i'm getting all users and respective profiles through rest-api using grape

@all_profiles =  @all_profiles || 
                TransitiveUserProfile.includes(:profile).where(
              "profile_id IN (?)", application.profile_ids)
present @users, with: Identity::V3::UserEntity, all_profiles: @all_profiles #@user = User.all - around 700 users

i have written UserEntity class

class UserEntity < Grape::Entity
  expose :id, as: :uniqueId
  expose :trimmed_userid, as: :userId
  expose :nachname, as: :lastName
  expose :vorname, as: :firstName
  expose :is_valid, as: :isValid
  expose :is_system_user, as: :isSystemUser
  expose :email
  expose :utc_updated_at, as: :updatedAt
  expose :applications_and_profiles


  def email  
    object.default_address_email
  end

   def applications_and_profiles
    app_profiles = @all_app_profiles.where(user_id: object.id).collect{|t|  {name: t.profile.unique_id, rights: t.profile.profilrechte} }
    [{:appl_id=>"test", :profiles=>app_profiles}]
  end

 end

i'm facing issue, when i try to get all users and profiles it takes more than 15 secs. facing issue in following code(taking time to get associated object).

 def email  
    object.default_address_email
  end

   def applications_and_profiles
    app_profiles = @all_app_profiles.where(user_id: object.id).collect{|t|  {name: t.profile.unique_id, rights: t.profile.profilrechte} }
    [{:appl_id=>"test", :profiles=>app_profiles}]
  end 

how can i resolve with efficient way(normally less than 5 secs)


Solution

  • app_profiles = @all_app_profiles.where(user_id: object.id).collect{|t| {name: t.profile.unique_id, rights: t.profile.profilrechte} }

    The above sql creates a N+1 problem, which will make the performace slower. You can check your logs regarding this. Better way to resolve the issue is use eager loading as shown below(As suggested by @max pleaner and @anothermh )

    app_profiles = @all_app_profiles.where(user_id: object.id).includes(:profile ).collect{|t| {name: t.profile.unique_id, rights: t.profile.profilrechte} }

    For more information regarding Eager Loading you can follow the below link:

    1) https://medium.com/@codenode/10-tips-for-eager-loading-to-avoid-n-1-queries-in-rails-2bad54456a3f

    2) https://blog.heroku.com/solving-n-plus-one-queries