Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

correct pattern of Ktor's HttpClient usage

Tags:

kotlin

ktor

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.

like image 56
Brilyantov Vadim Avatar answered Sep 01 '26 08:09

Brilyantov Vadim


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.

like image 42
Madhu Bhat Avatar answered Sep 01 '26 09:09

Madhu Bhat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!