Aman
Aman

Reputation: 370

How to handle rest api timeout

I want to create a POST api which does some processing in the backend and returns a response to the client. Unfortunately, the processing is time-consuming and the client can't wait until then.

One solution that I have thought is that, I will push the request in the queue and send a success response to the client. In the background, a worker can process the messages from the queue.

But the problem is that what if the operation fails, i.e., when the worker processes the message and it turns out to be an invalid request, how can I notify the client?

Upvotes: 1

Views: 9565

Answers (1)

VoiceOfUnreason
VoiceOfUnreason

Reputation: 57239

First, think through how you would implement this functionality on the web.

The user would follow a link to some form, fill it out, and submit it; the description of the form would tell the web browser to use the POST method, the browser would follow the specified process to take the form elements and construct the request that would be received by your web endpoint.

Your endpoint would validate the request, push the data to the queue, and then send back to the client... what?

Probably a html message saying "Hi, we received your request; it has been assigned tracking number 12345. We expect your results to be ready in 15 minutes; for further updates, visit this page."

That page would be represented as a hyperlink; a url that would point to another endpoint capable of reporting the status of the request. Since that's a safe operation, GET makes sense as the method, so the tracking number and other information needed by the endpoint would be encoded into the link.

That endpoint would in turn reply with a similar page; a description of the progress made, an estimate of when things might be ready, a link to follow to get an update.

Eventually, the work is done, and the endpoint replies with a message announcing that the work is complete, and here's a link to where you can find the result.

If something goes wrong, that same endpoint can be used to notify the client of what has gone sideways, and which corrective actions are available.

Make a machine readable version of that protocol, and you have a REST API.

Take the meta data embedded in the message, and lift it into the response headers, and you have a good REST api.

Upvotes: 3

Related Questions