Search code examples
javadropwizardjdbi

Timeout for Dropwizard's health checks?


I have two sql database connections for which health checks are automatically added by dropwizard. But when the application loses connection to one of them, the /healthcheck endpoint takes indefinitely long to respond, where I would want it to timeout after a few seconds.

I've already set the maxWaitForConnection setting, and I've also experimented with the various checkConnectionOn.. settings, but nothing helped.

UPDATE: The health check correctly fails if the server actively refuses the connection, but it hangs indefinitely if it's not the case, for instance, a network issue.

Is it possible to have sql health checks timeout at a specified time value whatever the problem is?


Solution

  • If the JDBC timeout settings aren't working you could always just wrap the DB check in a Future and limit how long it can run:

    protected Result check() throws Exception {
      ExecutorService executor = Executors.newSingleThreadExecutor();
      Future<Void> future = executor.submit(new DbConnectionChecker());
    
      try {
        future.get(SECONDS_THRESHOLD, TimeUnit.SECONDS);
      } catch (TimeoutException e) {
        return Result.unhealthy("DB timed out");
      }
      executor.shutdownNow();
      return Result.healthy();
    }
    

    Where DbConnectionChecker is something like:

    static class DbConnectionChecker implements Callable<Void> {
      public Void call() throws Exception {
        // Check your DB connection as you normally would
      }
    }
    

    Would be nice to figure out why the JDBC connection settings aren't working as expected, though.