user7731599
user7731599

Reputation:

correct pattern of Ktor's HttpClient usage

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?

Upvotes: 5

Views: 5178

Answers (3)

snorbi
snorbi

Reputation: 2890

It is better to reuse the HttpClient instance for performance reasons if the requests can be performed using the same configuration/settings.

But in some cases you have to create separate instances because the features of a HttpClient are determined by the engine and the plugins specified when creating the instance.
For example when using bearer authentication the HttpClient instances can be reused only when sending requests to the same resource server (with the same authorization configuration).
Similarly, if two requests should use different timeouts then they can be performed only by different HttpClients.

To summarize, a HttpClient instance should be created per "feature set", determined by the required engine and plugins.
A new HttpClient instance can be created easily by using the HttpClient.config { ... } method, which allows to customize an existing client, while sharing the underlying client engine.

Upvotes: 3

Brilyantov Vadim
Brilyantov Vadim

Reputation: 94

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.

Upvotes: 7

Madhu Bhat
Madhu Bhat

Reputation: 15173

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.

Upvotes: 4

Related Questions