Home > Back-end >  Why is there a "Get Status" step when implementing Async APIs w/ Polling?
Why is there a "Get Status" step when implementing Async APIs w/ Polling?

Time:08-19

Often times I see the following for polling:

  1. Send a request and get a unique ID back.
  2. Poll a "Status" endpoint, which tells the client when the request has been completed.
  3. Send a request to fetch the response.

Can't steps (2) and (3) be combined? If the response isn't ready, it'll return no response back, and some status indicating that. If it is ready, it'll return the response.

Why are (2) and (3) often separate steps?

CodePudding user response:

Is it ready is a boolean true/false and a response can be anything. In general it's easier to call "is it ready" then write logic to handle true and false than to write logic to get a response, determine if the response is not ready or is the data type you need.

In this way, the logic is all client side but if you combined them you'd need to have logic on both client and server (both to say it's not ready and to handle the actual response). You could do it but keeping it separate just keeps things neater.

CodePudding user response:

This pattern is generally defined by the HTTP 202 status code, which is the HTTP protocol's mechanism of initiating asynchronous requests.

We can think of a 202 response as indicating that a job has been created. If and when that job executes, it may (or may not) produce some business entity. Presumably the client receiving a 202 is ultimately interested in that business entity, which may (or may not) exist in the future, but certainly does not exist now, hence the 202 response.

So one simple reason for returning a pointer to a job status is because the job status exists now and we prefer to identify things that exist now rather than things that may (or may not) exist in the future. The endpoint receiving the request may not even be capable of generating an ID for the (future) business entity.

Another reason is status codes. A status endpoint returns a custom job status capable of describing unlimited potential states in which a job can exist. These job states are beyond the scope of HTTP status codes. The standard codes defined by the w3 already have precise definitions; and there simply is no standard HTTP status code that means "keep polling".

  • Related