Hi all. I’m looking for recommendations on how lon...
# ktor
d
Hi all. I’m looking for recommendations on how long to keep a Ktor
HttpClient
alive. I’m using the Ktor client inside a REST service, and that client will be used to call out to other services. A few options for lifetimes might include: • Create one Ktor client instance for the lifetime of the service instance. All outbound requests will be made through that one client instance (across all inbound request threads) until the service instance is shut down, at which point we would call
close()
on the Ktor client. • Create one Ktor client instance for the lifetime of the inbound HTTP request. In this case, I’d call
close()
after we’re done processing the inbound request. • Create one Ktor client instance for each outbound HTTP request that we need to make. In this case, we’d call
use { }
in order to make sure the instance was properly closed once the outbound request has been completed. What do you recommend, and why do you recommend it? Thanks!
h
It really depends on you configuration: plugins (Auth, Cache, Timeout, Retry) etc. If you just need a stateless one shot without any configs, of course you could recreate a new client every call. But even Ktor client is fast,
init
is not free: you would create (useless) objects every startup. I use the same client for each service/endpoint. Main reason is configuration: (token) authentication, default url, serialization.
r
Ktor client is built to handle multiple request running in parallel, so there should be no issues in using a single instance for entire service. Usually, this is a recommended approach, unless you have a specific use case.
b
A rule of thumb I'm using is one http client per target host. e.g. if you're calling google.com and bing.com often, you'd have two http clients in total
d
Excellent feedback. Thanks so much, everyone!