Skip to content

Deadlock eventually occurs in JdkHttpClient for certain requests #200

Closed

Description

@Billzabob

I am currently sharing the Java 8 HTTP client to create both the WebSocket client and the HTTP client. I make a single request with the HTTP client followed by connecting to a WebSocket and sending messages periodically. Eventually (always around 400 seconds later), everything hangs and CPU usage is locked at 100%.

This doesn't occur if:

  • I create a separate client and WebSocket client using .simple[IO]
  • I don't make the initial request with the client
  • I request other URLs with the client

Since it doesn't happen with every URL, I'm assuming it has something to do with the endpoint I'm hitting. It gives the following response:

Response(
  status=200,
  headers=Headers(
    cf-cache-status: DYNAMIC,
    cf-ray: 57d4a1eb4eaaa062-SLC,
    connection: keep-alive,
    content-type: application/json,
    date: Wed, 01 Apr 2020 19:14:20 GMT,
    expect-ct: max-age=604800,
    report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct",
    server: cloudflare,
    set-cookie: <REDACTED>,
    set-cookie: <REDACTED>,
    strict-transport-security: max-age=31536000; includeSubDomains,
    transfer-encoding: chunked,
    via: 1.1 google,
    x-envoy-upstream-service-time: 26,
    x-ratelimit-bucket: 41f9cd5d28af77da04563bcb1d67fdfd,
    x-ratelimit-limit: 2,
    x-ratelimit-remaining: 1,
    x-ratelimit-reset: 1585768466,
    x-ratelimit-reset-after: 5
  )
)

{
  "url": "wss://gateway.discord.gg",
  "shards": 1,
  "session_start_limit": {
    "total": 1000,
    "remaining": 992,
    "reset_after": 23572680
  }
}

I tried to put together a minimized example of what I'm seeing here:

import cats.effect._
import cats.implicits._
import fs2.Stream
import java.net.http.HttpClient
import org.http4s.client.jdkhttpclient._
import org.http4s.client.jdkhttpclient.WSFrame._
import org.http4s._
import org.http4s.headers._
import org.http4s.implicits._
import scala.concurrent.duration._

object Main extends IOApp {
  override def run(args: List[String]): IO[ExitCode] = {
    IO(HttpClient.newHttpClient).map(client => (JdkHttpClient[IO](client), JdkWSClient[IO](client))).flatMap {
      case (client, wsClient) =>
        client.expect[String](Request[IO](uri = uri"https://discordapp.com/api/gateway/bot", headers = Headers.of(headers))) >> connection(wsClient)
          .compile
          .drain
          .as(ExitCode.Success)
    }
  }

  // Removed since it's private info
  val token: String = ???

  val headers =
    Authorization(Credentials.Token("Bot".ci, token))

  def connection(wsClient: WSClient[IO]) =
    Stream
      .resource(wsClient.connectHighLevel(WSRequest(uri"wss://echo.websocket.org")))
      .flatMap { connection =>
        printResponses(connection).concurrently(
          Stream
            .awakeEvery[IO](1.seconds)
            .evalMap(time => connection.send(Text(s"${time.toSeconds} seconds")))
        )
      }

  def printResponses(connection: WSConnectionHighLevel[IO]): Stream[IO, Unit] = {
    connection.receiveStream
      .collect {
        case Text(data, _) => data
      }
      .evalMap(s => IO(println(s)))
  }

}

This prints out:

1 seconds
2 seconds
3 seconds
4 seconds
5 seconds
6 seconds
7 seconds
8 seconds
...
393 seconds
394 seconds
395 seconds
396 seconds
397 seconds

And then it hangs and CPU usage is stuck at 100%

Activity

  1. Billzabob commented on Apr 1, 2020

    @Billzabob
    Author

    I was able to narrow this down even further. It seems to just be related to the client. The following code also hangs and pegs CPU at 100% after about 460 seconds:

    import cats.effect._
    import cats.implicits._
    import fs2.Stream
    import org.http4s._
    import org.http4s.client.jdkhttpclient._
    import org.http4s.headers._
    import org.http4s.implicits._
    import scala.concurrent.duration._
    
    object Main2 extends IOApp {
      override def run(args: List[String]): IO[ExitCode] = {
        JdkHttpClient.simple[IO].flatMap { client =>
          Stream
            .awakeEvery[IO](5.seconds)
            .evalTap(_ => client.expect[String](Request[IO](uri = uri"https://discordapp.com/api/gateway/bot", headers = Headers.of(headers))))
            .evalTap(time => IO(println(s"${time.toSeconds} seconds")))
            .compile
            .drain
            .as(ExitCode.Success)
        }
      }
    
      val token = ???
    
      val headers =
        Authorization(Credentials.Token("Bot".ci, token))
    
    }
    
  2. changed the title [-]Deadlock occurs when sharing JDK client `JdkHttpClient` and `JdkWSClient`[/-] [+]Deadlock eventually occurs in `JdkHttpClient` for certain requests[/+] on Apr 1, 2020
  3. ChristopherDavenport commented on Apr 1, 2020

    @ChristopherDavenport
    Member

    Since this is associated in some way with the JDK, which JDK is being used?

  4. Billzabob commented on Apr 1, 2020

    @Billzabob
    Author

    @ChristopherDavenport I'm using JDK 11
    Specifically:

    openjdk version "11.0.2" 2019-01-15
    OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
    OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)
    
  5. Billzabob commented on Apr 1, 2020

    @Billzabob
    Author

    Any idea what it could be about this particular response that causes this? I tried testing this against a few other URLs and wasn't able to reproduce the issue.

  6. amesgen commented on Apr 1, 2020

    @amesgen
    Member

    How do I create such a token? I created a discord "application", added a bot and got a token, but I get 401 unauthorized.

  7. amesgen commented on Apr 1, 2020

    @amesgen
    Member

    I can confirm that increased cpu usage does not happen on e.g. https://discordapp.com (no api/gateway/bot).

    Can you test if this happens with #191 ? It is the only thing I can think of right now.

  8. Billzabob commented on Apr 1, 2020

    @Billzabob
    Author

    I'm not sure why you're getting a 401. It's been a while since I created my bot but I think that's all I did. I just ran it using java.net.http.HttpClient directly and it never froze. I also am running it with #191 right now and so far it's made it further than before so maybe that's the problem. I'll leave it running and let you know if it ever hangs 👍

  9. Billzabob commented on Apr 1, 2020

    @Billzabob
    Author

    It's hung again :( After running for 770 seconds it stopped and once again I'm seeing 100% CPU usage.

  10. amesgen commented on Apr 1, 2020

    @amesgen
    Member

    Ah, I thought I had to change "Bot".ci, now it works. Now staring at CPU usage...

  11. amesgen commented on Apr 1, 2020

    @amesgen
    Member

    It has been running for 1300 seconds and I noticed nothing suspicious about CPU or memory usage. I am on master, not on #191.

    My Java version:

    openjdk version "11.0.6" 2020-01-14
    OpenJDK Runtime Environment (build 11.0.6+10)
    OpenJDK 64-Bit Server VM (build 11.0.6+10, mixed mode)
    

    Can you test it with this version?

  12. amesgen commented on Apr 1, 2020

    @amesgen
    Member

    Maybe JDK-8221395 is the reason?

  13. Billzabob commented on Apr 1, 2020

    @Billzabob
    Author

    I was hopeful. I tried it with that JDK but it's still freezing up for me :( This time it did at 430 seconds.

  14. amesgen commented on Apr 1, 2020

    @amesgen
    Member

    Can you turn on logging?

  15. amesgen commented on Apr 2, 2020

    @amesgen
    Member

    Uh, now it froze for me, after 4010 seconds (accidentally cancelled the first run after ~1800 seconds).

  16. 19 remaining items

  17. amesgen commented on Apr 3, 2020

    @amesgen
    Member

    There really is not much code left in comparison to the (non-freezing) plain Java version, I will try to create a minimal example tomorrow.

  18. amesgen commented on Apr 3, 2020

    @amesgen
    Member

    Ok, "good" news: Both the freeze and the too many concurrent streams issue are not http4s-related.


    Freezes

    Code (HTTP 1.1)
    import java.net.URI
    import java.net.http.HttpClient.Version
    import java.net.http.HttpRequest.BodyPublishers
    import java.net.http.HttpResponse.BodyHandlers
    import java.net.http.{HttpClient, HttpRequest}
    import java.time.Instant
    import java.util.concurrent.{CancellationException, CompletionException, CompletionStage}
    
    import cats.effect._
    import cats.effect.implicits._
    import cats.implicits._
    import fs2.Stream
    
    import scala.concurrent.duration._
    
    object Main extends IOApp {
    
      override def run(args: List[String]): IO[ExitCode] =
        for {
          client <- IO(HttpClient.newHttpClient())
          runRequest = fromCompletionStage(
            IO(
              client.sendAsync(
                HttpRequest
                  .newBuilder()
                  .uri(URI.create("https://discordapp.com/api/gateway/bot"))
                  .method("GET", BodyPublishers.noBody())
                  .header("Authorization", s"Bot $token")
                  .version(Version.HTTP_1_1)
                  .build(),
                BodyHandlers.ofString()
              )
            )
          )
          _ <- Stream
            .awakeEvery[IO](5.seconds)
            .evalTap(_ => runRequest.flatMap(s => IO(println(s))))
            .evalTap(time => IO(println(s"[${Instant.now()}] ${time.toSeconds} seconds")))
            .compile
            .drain
        } yield ExitCode.Success
    
      def fromCompletionStage[F[_], CF[x] <: CompletionStage[x], A](
          fcs: F[CF[A]]
      )(implicit F: Concurrent[F], CS: ContextShift[F]): F[A] =
        fcs.flatMap { cs =>
          F.async[A] { cb =>
              cs.handle[Unit] { (result, err) =>
                err match {
                  case null => cb(Right(result))
                  case _: CancellationException => ()
                  case ex: CompletionException if ex.getCause ne null => cb(Left(ex.getCause))
                  case ex => cb(Left(ex))
                }
              }
              ()
            }
            .guarantee(CS.shift)
        }
    
      val token = "foo"
    }
    

    Also without fs2, only cats-effect as a dependency:

    Code without fs2 (HTTP 1.1)
    import java.net.URI
    import java.net.http.HttpClient.Version
    import java.net.http.HttpRequest.BodyPublishers
    import java.net.http.HttpResponse.BodyHandlers
    import java.net.http.{HttpClient, HttpRequest}
    import java.time.{Instant, Duration => JDuration}
    import java.util.concurrent.{CancellationException, CompletionException, CompletionStage}
    
    import cats.effect._
    import cats.effect.implicits._
    import cats.implicits._
    
    import scala.concurrent.duration._
    
    object Main extends IOApp {
    
      override def run(args: List[String]): IO[ExitCode] =
        for {
          client <- IO(HttpClient.newHttpClient())
          runRequest = fromCompletionStage(
            IO(
              client.sendAsync(
                HttpRequest
                  .newBuilder()
                  .uri(URI.create("https://discordapp.com/api/gateway/bot"))
                  .method("GET", BodyPublishers.noBody())
                  .header("Authorization", s"Bot $token")
                  .version(Version.HTTP_1_1)
                  .build(),
                BodyHandlers.ofString()
              )
            )
          )
          start <- IO(Instant.now())
          ec <- (runRequest <* IO.sleep(5.seconds)).flatMap(s =>
            IO {
              println(s.statusCode)
              val now = Instant.now()
              println(s"[$now] ${JDuration.between(start, now).toSeconds} seconds")
            }
          ).foreverM
        } yield ec
    
      def fromCompletionStage[F[_], CF[x] <: CompletionStage[x], A](
          fcs: F[CF[A]]
      )(implicit F: Concurrent[F], CS: ContextShift[F]): F[A] =
        fcs.flatMap { cs =>
          F.async[A] { cb =>
              cs.handle[Unit] { (result, err) =>
                err match {
                  case null => cb(Right(result))
                  case _: CancellationException => ()
                  case ex: CompletionException if ex.getCause ne null => cb(Left(ex.getCause))
                  case ex => cb(Left(ex))
                }
              }
              ()
            }
            .guarantee(CS.shift)
        }
    
      val token = "foo"
    
    }
    

    If I use HTTP 2 instead of HTTP 1.1 in the second example, I can reproduce the too many concurrent streams issue, so this issue is definitely unrelated to #207 sry, I am forgetting what I was testing. Actually, I also changed the body handler from BodyHandlers.ofString to BodyHandlers.ofPublisher in order to not close the connections properly, so it is actually expected to reproduce the too many concurrent streams issue... Sry for the confusion.

    Code without fs2 (HTTP 2 and intended connection leakage)
    import java.net.URI
    import java.net.http.HttpClient.Version
    import java.net.http.HttpRequest.BodyPublishers
    import java.net.http.HttpResponse.BodyHandlers
    import java.net.http.{HttpClient, HttpRequest}
    import java.time.{Instant, Duration => JDuration}
    import java.util.concurrent.{CancellationException, CompletionException, CompletionStage}
    
    import cats.effect._
    import cats.effect.implicits._
    import cats.implicits._
    
    import scala.concurrent.duration._
    
    object Main extends IOApp {
    
      override def run(args: List[String]): IO[ExitCode] =
        for {
          client <- IO(HttpClient.newHttpClient())
          runRequest = fromCompletionStage(
            IO(
              client.sendAsync(
                HttpRequest
                  .newBuilder()
                  .uri(URI.create("https://discordapp.com/api/gateway/bot"))
                  .method("GET", BodyPublishers.noBody())
                  .header("Authorization", s"Bot $token")
                  .version(Version.HTTP_2)
                  .build(),
                BodyHandlers.ofPublisher()
              )
            )
          )
          start <- IO(Instant.now())
          ec <- (runRequest <* IO.sleep(5.seconds)).flatMap(s =>
            IO {
              println(s.statusCode)
              val now = Instant.now()
              println(s"[$now] ${JDuration.between(start, now).toSeconds} seconds")
            }
          ).foreverM
        } yield ec
    
      def fromCompletionStage[F[_], CF[x] <: CompletionStage[x], A](
          fcs: F[CF[A]]
      )(implicit F: Concurrent[F], CS: ContextShift[F]): F[A] =
        fcs.flatMap { cs =>
          F.async[A] { cb =>
              cs.handle[Unit] { (result, err) =>
                err match {
                  case null => cb(Right(result))
                  case _: CancellationException => ()
                  case ex: CompletionException if ex.getCause ne null => cb(Left(ex.getCause))
                  case ex => cb(Left(ex))
                }
              }
              ()
            }
            .guarantee(CS.shift)
        }
    
      val token = "foo"
    
    }

    In addition to the synchronous "plain Java" version above, here also a version with sendAsync.

    Code without fs2 (HTTP 2)
    import java.net.*;
    import java.net.http.*;
    import java.net.http.HttpClient.Version;
    import java.net.http.HttpRequest.BodyPublishers;
    import java.net.http.HttpResponse.BodyHandlers;
    import java.util.*;
    import java.util.concurrent.*;
    
    class Main {
      public static void main(String[] args) throws Exception {
        System.out.println("starting");
        var http = HttpClient.newHttpClient();
        var token = args[0];
        var req = HttpRequest.newBuilder()
                      .uri(URI.create("https://discordapp.com/api/gateway/bot"))
                      .header("Authorization", "Bot " + token)
                      .version(HttpClient.Version.HTTP_2)
                      .build();
        int s = 0;
        var fut = CompletableFuture.completedFuture(0);
        while (true) {
          Thread.sleep(5000);
          s += 5;
          final var ss = s;
          fut =
              fut.thenCompose(
                     $ -> http.sendAsync(req, HttpResponse.BodyHandlers.ofString()))
                  .thenApply(res -> {
                    System.out.println("status code " + res.statusCode());
                    System.out.println(ss);
                    return 0;
                  });
        }
      }
    }
    

    Both HTTP 1.1 and HTTP 2 work fine, without any freezes.

  19. amesgen commented on Apr 3, 2020

    @amesgen
    Member

    This GH issue is already pretty big, and we have two (probably unrelated subissues), and none of them are related to http4s or http4s-jdk-http-client directly. Do we want to move the discussion elsewhere?

  20. amesgen commented on Apr 3, 2020

    @amesgen
    Member

    Ha, I just got a freeze with this "plain Java" code:

    Code
    import java.net.*;
    import java.net.http.*;
    import java.net.http.HttpClient.Version;
    import java.net.http.HttpRequest.BodyPublishers;
    import java.net.http.HttpResponse.BodyHandlers;
    import java.util.*;
    import java.util.concurrent.*;
    
    class Main {
      public static void main(String[] args) throws Exception {
        System.out.println("starting");
        var http = HttpClient.newHttpClient();
        var token = args[0];
        var req = HttpRequest.newBuilder()
                      .uri(URI.create("https://discordapp.com/api/gateway/bot"))
                      .header("Authorization", "Bot " + token)
                      .version(HttpClient.Version.HTTP_2)
                      .build();
        int s = 0;
        var fut = CompletableFuture.completedFuture(0);
        while (true) {
          Thread.sleep(5000);
          s += 5;
          final var ss = s;
          fut =
              fut.thenCompose(
                     $ -> http.sendAsync(req, HttpResponse.BodyHandlers.ofPublisher()))
                  .thenApply(res -> {
                    System.out.println("status code " + res.statusCode());
                    System.out.println(ss);
                    return 0;
                  });
        }
      }
    }

    Now this seems to indicate that the freeze issue is indeed a Java 11 issue.

    @Billzabob Can you confirm this?

  21. Billzabob commented on Apr 3, 2020

    @Billzabob
    Author

    Yep! That froze for me too after 1280 seconds.

  22. Billzabob commented on Apr 4, 2020

    @Billzabob
    Author

    I tried modifying your example and changing BodyHandlers.ofPublisher() to BodyHandlers.discarding() and now it's been going for 2850 seconds without hanging. Think it could have something to do with that? I'll leave it running to make sure. I know nothing about java.util.concurrent.Flow though.

  23. amesgen commented on Apr 4, 2020

    @amesgen
    Member

    Yes, that is still confusing me:

    • When using BodyPublishers.ofPublisher like in the "intended connection leakage" example from here, it results in a too many concurrent streams exception. This seems very reasonable.
    • When using BodyPublishers.ofPublisher with the plain Java version, we get a freeze (I confirmed that it still is the SSL issue). This is weird, I would expect an too many concurrent streams exception.

    But when using an "eager" BodyPublisher like discarding or ofString, the cats-effect version does freeze (see here), although plain Java seems to work fine.

  24. Billzabob commented on Apr 4, 2020

    @Billzabob
    Author

    Wow. That is extremely confusing. This type of stuff is such a pain to track down. Especially since it takes minutes or hours to determine if it's going to freeze or not.

  25. lhns commented on Aug 9, 2020

    @lhns

    I think I'm also having this issue with my simple one-file http-retry-proxy microservice:
    https://github.com/LolHens/http-wait/blob/cd87c443e76812dbecaeae9b7c51f5004f6aa181/src/main/scala/de/lolhens/httpwait/Main.scala
    I am not using websockets, just simple http requests. I run this as a graal native-image in a docker container.
    This runs fine sometimes for a few days and sometimes for weeks but now and then it just locks up and I also get 100% cpu on the container.
    Maybe this info helps to narrow it down. For now I will try switching to another client backend.

  26. amesgen commented on Aug 9, 2020

    @amesgen
    Member

    Thanks for reminding me of this issue @LolHens

    Note that this issue is not caused by http4s-jdk-http-client, but rather by some weird interaction of cats-effect and TLSv1.3 stuff (maybe cats-effect only increases the likelihood of this TLS bug to occur). src

    There two easy workarounds (also see our docs):

    • Disable TLSv1.3 (also see here)
    • Use Java > 11
  27. lhns commented on Aug 9, 2020

    @lhns

    Thanks for the quick info! I will try disabling TLSv1.3 then.

  28. added a commit that references this issue on Aug 10, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions