https://kotlinlang.org logo
#ktor
Title
# ktor
d

dave08

03/14/2023, 2:50 PM
What's the recommended way to set a timeout on an endpoint in a Ktor Server?
a

Aleksei Tirman [JB]

03/14/2023, 2:59 PM
What kind of timeout do you mean?
d

dave08

03/14/2023, 3:00 PM
Some of my requests are hanging for more than an hour according to Istio...! I need to timeout such long requests...
a

Aleksei Tirman [JB]

03/14/2023, 3:01 PM
So do you mean stale connections?
d

dave08

03/14/2023, 3:03 PM
I'm not sure how these requests are hanging so much... on the client side I have this:
Copy code
okHttpClient.newBuilder().apply {
			connectTimeout(30, TimeUnit.SECONDS)
			readTimeout(1, TimeUnit.MINUTES)
			writeTimeout(1, TimeUnit.MINUTES)
		}.build()
image.png
@Aleksei Tirman [JB] I think it happens to hang while receiving headers or form parts since I have KotlinX serialization errors with what seems to be partial json being sent when these long requests take place...
It's confirmed in my production environment that a bunch of requests don't have complete headers or multipart bodies, and they hang for a good while... is this normal?
c

CLOVIS

03/14/2023, 4:59 PM
If you mean for a single timeout, you can just add
Copy code
withTimeout(5000) {
    …rest of your code…
}
https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/with-timeout.html If you want to apply it to your entire application, I think you'll have to create a custom plugin. It's not hard to do
d

dave08

03/14/2023, 5:00 PM
Yeah, that's what I was thinking... I was just wondering if I'm not the only one who has these problems, there might already be something out there that's better... 😉
172 Views