correct pattern of Ktor's HttpClient usage

Viewed 1583

What's the correct pattern of usage for HttpClient in KTOR. Should I use it like singleton per app lifecycle, or should I create it per each request?

2 Answers

I would say that you may have more than one client per app if you need to connect to more than one logical services. But if you are dealing with one single HTTP server it's better to have one client because it establishes and holds a connection with server. It also allocates the following resources: prepared threads, coroutines and connections. If you have multiple clients you can potentially run out of these resources.

Should I use it like singleton per app lifecycle, or should I create it per each request

Creation of a http client instance is usually a bit resource intensive, hence you should not create an instance of client for every request. You should create just one http client instance per app's lifecycle, injected wherever required in your app, ensuring that

  • you have used the right http client configurations like the thread pool size, timeouts etc
  • you are releasing the resources upon the app's shutdown.

The client can be configured with HttpClientEngineConfig(doc) or any of its inheritors. More details in the documentation here.

Related