API Best Practices – Is It Bad Practice for Backend to Call 3rd Party APIs Synchronously?

apiserver

I use a third party API on my webapp that is accessed when the user requests a particular ressource. I'm worried that the successive API calls happening upon user's request might cause the user to wait a very long time and slow down my system (since the thread processing the initial request is also waiting on these API calls to return).

so basically client -> server ->x3 third party API (three successive calls are needed)

Details:
these API calls login in the user with the 3rd party system and return a session token. Currently using Django in the backend.

Is doing this synchronously always a bad idea this way? I've considered creating an asynchronous architecture instead and serving it to the user via websocket, but I'm hesitating because of the perceived added complexity of design.

Best Answer

Synchronous calls for this purpose are fine, especially if you need the result of the call to continue processing the request.

You should do that asynchronously if you have a reason to do so. Many people don't realize it but doing something asynchronous or in parallel can create a lot of problems and there is a lot of complexity even it's well hidden (like the C# async/await).

So, if you

  • can continue processing the request without having the response from the 3rd party API but that data must be in your response (i.e. you can do other things in parallel with waiting for the response)
  • don't really need it to continue but it's nice to have it, however doesn't really matter if it is or isn't in your response (i.e. you can do other things in parallel with it but don't wait for it - if it doesn't return in time, you can send your response anyway)
  • don't need it at all for this request and can send it to the client later

you should do it asynchronously. The first case is probably most common.

In your particular case, you probably need the user to be authenticated and authorized before continuing processing the request. So I would do it synchronously. Another question are the 3 successive calls. Can they be in parallel? Then you can do it and wait for all 3 to be completed. If not, can you ask for changing the API to allow for only one call? This would be the 'right thing to do' however it's usually impossible.

Related Topic