Marcin_S
Marcin_S

Reputation: 539

How to handle long API request

I have an API which runs a query on database. Since the query execution time can be long, like 3 min to 10 min, my load balancer is returning "upstream request timeout", but I can see the query is submitted to the datasource, but for the end user it's showing the wrong message. How to take care of this scenario?

My function

@PostMapping("/run/{QueryId}")
public void runQuery(@PathVariable String QueryId) {
     // This method takes long time
     querySchedulerService.runQuery(QueryId);
} 

Upvotes: 1

Views: 1413

Answers (1)

4EACH
4EACH

Reputation: 2197

Controller:

class SomeController{
 @PostMapping("/run/{QueryId}")
    public ResponseEntity<Void> runQuery(@PathVariable String QueryId) {
         // This method takes long time
         querySchedulerService.runQuery(QueryId);
         return new ResponseEntity<>(HTTP_STATUS.ACCEPTED);
    } 
}

Service:

@Service
class QuerySchedulerService{

    @Async
    public void runQuery(Query query){
    // Do somthing
    }
}

By adding @EnableAsync annotation in main Application class you can use @Async annotation

On every time that runQuery will called it will run in new thread.

@EnableAsync
class Application{

}

Upvotes: 1

Related Questions