Skip to content

Conversation

@VSidhArt
Copy link

@VSidhArt VSidhArt commented Apr 3, 2019

Проблема импорта данных

импорт из файла large.json был не возможен т.е. занимал огромное количество времени
для feedback loop был выбран файл small.json, который исполнялся 7.5 сек.
Анализ логов выявил, что операции insert быстрые, но их слишком много.
Для вставки batches, использовал gem activerecord-import, позволяющий вставлять пачками, используя при это active record валидации, время уменьшилось до 3 сек, но еще оставлось много запросов к базе типа find_by_name, для уменшения кол-ва запросов, было принято решение кешировать объекты в памяти, что позволило скротить время до 0.5 сек.
Файл large.json стал загружаться за приемлемое - 30 сек время

Проблема отображения расписаний

После загрузки large.json в базу, оказалось что страница автобусы/Самара/Москва загружается очень долго, результат загрузки(для тестирования использовал k6)

avg=11.54s    min=11.26s   med=12.94s   max=15.41s   p(90)=13.52s   p(95)=14.47s 

Было выявлено 2 основные проблемы:

  1. N+1, у trips вызывались bus и services, добавлен eager_load
  2. Отсутсвтвие индексов, добавлены индексы
    Результат:
avg=7.74s    min=7.61s   med=7.68s   max=7.93s    p(90)=7.88s    p(95)=7.91s

Доп оптимзации:

Кешировние partial _service

avg=1.78s   min=1.7s    med=1.79s   max=1.87s    p(90)=1.83s    p(95)=1.84s

Удаление partial _delimetr

avg=1.51s   min=1.39s   med=1.51s   max=1.56s    p(90)=1.54s    p(95)=1.55s

Copy link
Owner

@spajic spajic left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хорошая работа, респект за тесты!

@@ -0,0 +1,10 @@
class AddIndexesToTrip < ActiveRecord::Migration[5.2]
disable_ddl_transaction!
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

disable_ddl_transaction!

def change
add_index :trips, [:from_id, :to_id], algorithm: :concurrently
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 Плюс за concurrently

end

it "doesn't send unnecessary requests to db" do
expect { get :index, params: { from: trip.from.name , to: trip.to.name } }.not_to exceed_query_limit(2)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍 за 'rspec-sqlimit'


puts "Controller time: #{time}"

expect(time).to be < 0.006
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

end
let!(:trip) { Trip.preload(:from, :to).take }

it 'correct trips count' do
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Хорошо читается, когда получается согласованное предложение, например it 'has correct trips count'

expect(assigns(:trips).size).to eq(9)
expect(assigns(:from).name).to eq(trip.from.name)
expect(assigns(:to).name).to eq(trip.to.name)
end
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лишний отступ

@@ -0,0 +1,44 @@
# frozen_string_literal: true

require 'rails_helper'
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

requireы было бы лучше вынести в rails_helper и реквайрить уже его

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants