Save Visit is taking lot of time when we have more than 1000 encounters associated with a Visit


Please find the problem and analysis done

Problem :

In one of our bahmni implementations, there are patients in program module who has an open visit which is longer than 1 year duration and visit has more than 1000 encounters on an avg.(~1700). When we are trying to add any medication, form data or loading patient/visit dashboards, it is taking whole lot of time(more than 3 mins if we have good network, more than 6 mins if we have bad network).

Findings from code: If we take an example of saving medication for such patient, we are making saveVisit(visit) call multiple times (one and two) as part of entire medication post call.Each time we call this saveVisit(visit), its taking nearly 2 mins. Moreover saving the visit to db is not taking much time, the actual time consuming task is to load all the encounters associated to a visit every time we save a visit.

Also, In visit.hbm file we mentioned configuration for encounters as lazy load true, which means before saving a visit it will try to load all the encounters associated to that visit.

One approach that we tried to confirm the same, we have enabled the mysql general_log to see what exactly is happening as part of saveVisit(visit) method call. As expected it is trying to load all the encounters associated to visit.


Do we need to save all the encounters when we save a visit?

Do we need to call saveVisit even for the existing visit?

We really appreciate any inputs on this issue as this is a blocker for our implementation

@binduak @angshuonline @mksrom @vmalini @swedhan @thomasrod @michaelbontyes @muhima08 @buvaneswariarun @mksd @dkayiwa @wyclif @darius @ssmusoke @mogoodrich @urooj @kirity @matirp235


@mksd @dkayiwa @angshuonline @mogoodrich
We have added a condition to call saveVisit() method only when there is a new visit created. We are ignoring this call when the visit is already there in the database. This has improved the performance from 3 mins to 45 sec. The below is the place where we have added the if condition

We are saving the newly created encounter under the visit even before calling saveVisit() method and after calling the saveVisit(). So ignoring the call for existing visit is not having any impact. We have tested all the basic flows with the change in place.

If the approach is fine, we will create a OpenMRS ticket and raise the PR for the same. Thanks!

@kirity @swedhan @buvaneswariarun @vmalini @vinisha

1 Like

Ah, thanks @binduak. In our implementation we don’t use the EmrEncounterService functionality to defer to you guys as to what works best!

1 Like

Thanks @binduak, that all seems to make sense.

Furthermore this could have be done in findOrCreateVisit(..) before returning. I find it weird that currently this method sometimes returns a visit already saved, sometimes not.

1 Like

Looks fine to me.

1 Like

@mksd @angshuonline Created a ticket and raised the PR