FFT-95 Optimise edit forecast database queries #546
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
I set out to improve the performance of the edit forecast page. On my local machine it took over 6 seconds just to fetch the initial HTML.
Our local dataset contains over 400 rows in the table on that page, so I suspected we had an n+1 database query problem. After some digging it turns out I was right and there were over 17,000 queries!
After a couple of days spent optimising code, mostly through the use of
select_related
andprefetch_related
, I've managed to get the number of queries down to 13 and the page load time down to around 300ms!Here is a brief list of the optimisations:
select_related
andprefetch_related
where neededcurrent_financial_year
on therequest
objectcached_property
to view methods being used in the templatecurrent_financial_year
as context into the financial code serializerThere was a more ambitious optimising around the
current_financial_year
using aContextVar
, but I chose to leave it out and go with storing it on the request object as it's simpler.The react code is now the bottleneck on that page :)