private Pair<DbEndpoint, Connection> connectToBestAvailableEndpoint(boolean needWritable) throws SQLException {
    SQLException lastException = null;
    for (DbEndpoint candidateEndpoint : sortedDbEndpoints) {
      if (!isBetterEndpoint(candidateEndpoint, connectedEndpoint)) {
        // What we have is the best we can do.  Is it good enough?
        if (needWritable && !connectedEndpoint.isWriteable()) {
          throw Optional.ofNullable(lastException).orElse(noWritableEndpointException);
        } else {
          return new Pair<>(connectedEndpoint, activeConnection);
        }
      }
      if (needWritable && !candidateEndpoint.isWriteable()) {
        throw Optional.ofNullable(lastException).orElse(noWritableEndpointException);
      }

      // Attempt to connect to candidate endpoint
      Properties credentials = new Properties();
      credentials.setProperty("user", candidateEndpoint.getUsername());
      credentials.setProperty("password", candidateEndpoint.getPassword());
      try {
        Connection connection = mysqlDriver.connect(candidateEndpoint.getUrl(), credentials);
        //since we will support auto purge, it's better that the isolation level con be programmed by config.
        if (config != null && !config.transactionIsolationLevel.equals(TransactionIsolationLevel.TRANSACTION_NONE)) {
          connection.setTransactionIsolation(
              convertStringToTransactionLevel(config.transactionIsolationLevel.name()));
        }
        metrics.connectionSuccessCount.inc();
        return new Pair<>(candidateEndpoint, connection);
      } catch (SQLException e) {
        logger.warn("Unable to connect to endpoint {} due to {}", candidateEndpoint.getUrl(), e.getMessage());
        metrics.connectionFailureCount.inc();
        if (isCredentialError(e)) {
          // fail fast
          throw e;
        } else {
          lastException = e;
        }
      }
    }

    throw Optional.ofNullable(lastException).orElse(noEndpointException);
  }
Connect to the best available database instance that matches the specified criteria.<br/>
Order of preference for instances to connect to:
<OL>
   <LI/> Writeable instance in local colo
   <LI/> Writable instance in any colo
   <LI/> Read-only instance in local colo (if needWritable is false)
   <LI/> Read-only instance in any colo (if needWritable is false)
 </OL>
@param needWritable whether the endpoint needs to be writable
@return a pair of {@link DbEndpoint} and corresponding {@link Connection}.
@throws SQLException if connection could not be made to a suitable endpoint.
ambry-mysql/src/main/java/com/github/ambry/mysql/MySqlDataAccessor.java