Spring boot - run Pagination (Result and Count) in parallel

Viewed 31

I have a Spring Boot Backend written in Kotlin. We're doing the classic pagination thing, with one query for the results with an offset, the other one counts the whole results, so we know how many more pages there are.

The queries are quite complicated. The count Query takes up to 10 seconds to run, the result query around 3-6 seconds. So, whenever someone changes the page, there is a loading time for 16 seconds - simply too much.

Beside from working on the queries, we would like to make both these queries run in parallel, since at the moment, the first one waits for the execution of the second one to start.

This is my code:

val listQuery = entityManager.createNativeQuery(listString, clazz)
val countQuery = entityManager.createNativeQuery(countString)

// These who lines should be executed in parallel
val count = (countQuery.resultList[0] as BigInteger).toInt()
val results = listQuery.resultList.distinct().map { clazz.cast(it) }

I was already playing around with kotlin coroutines, but that didn't fully work (maybe, because I implemented them the wrong way?) If someone wishes, I could post the code how I tried, but not sure if that will help, since I'd like to have a good practice answer rather than someone telling me how to fix my potentially bad code anyways.

Thank you for your time and your answers, really appreciate it!

0 Answers
Related