Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

MB_JDBC_DATA_WAREHOUSE_CONNECTION_POOL_CHECKOUT_TIMEOUT_MS (#76941)

Alexander Polyankinc32c55c589d6
diff --git a/src/metabase/driver/settings.clj b/src/metabase/driver/settings.clj
index a02305d7ffa..27126e9260a 100644
--- a/src/metabase/driver/settings.clj
+++ b/src/metabase/driver/settings.clj
@@ -127,6 +127,21 @@
For setting the maximum,
see [MB_APPLICATION_DB_MAX_CONNECTION_POOL_SIZE](#mb_application_db_max_connection_pool_size).")
+(defsetting jdbc-data-warehouse-connection-pool-checkout-timeout-ms
+ "Number of milliseconds a query will wait for a free data-warehouse connection once the c3p0 pool has hit
+ [[jdbc-data-warehouse-max-connection-pool-size]] before giving up. Maps to c3p0's `checkoutTimeout`. `0` waits
+ indefinitely (the old, unbounded behavior); a positive value fails fast, which the query processor surfaces to the
+ frontend as an HTTP 503 (Service Unavailable) rather than letting the request queue grow without limit."
+ :visibility :internal
+ :export? false
+ :type :integer
+ :default 0
+ :audit :getter
+ :doc "When every data-warehouse connection is in use, additional queries wait for one to free up. This is the
+ maximum time (in milliseconds) a query will wait before failing with a \"service unavailable\" (HTTP 503) error
+ instead of queueing indefinitely. Raise it if you routinely run more concurrent queries than
+ MB_JDBC_DATA_WAREHOUSE_MAX_CONNECTION_POOL_SIZE and would rather have them wait; set it to `0` to wait forever.")
+
(def ^:dynamic ^Long *query-timeout-ms*
"Maximum amount of time query is allowed to run, in ms."
(u/minutes->ms (db-query-timeout-minutes)))
diff --git a/src/metabase/driver/sql_jdbc/connection.clj b/src/metabase/driver/sql_jdbc/connection.clj
index e96909f3b75..fd9d7b19299 100644
--- a/src/metabase/driver/sql_jdbc/connection.clj
+++ b/src/metabase/driver/sql_jdbc/connection.clj
@@ -105,6 +105,16 @@
"minPoolSize" 0
"initialPoolSize" 0
"maxPoolSize" (driver.settings/jdbc-data-warehouse-max-connection-pool-size)
+ ;; [From dox] The number of milliseconds a client calling getConnection() will wait for a Connection to be
+ ;; checked-in or acquired when the pool is exhausted. Zero means wait indefinitely. Setting any positive value will
+ ;; cause the getConnection() call to time out and break with an SQLException after the specified number of
+ ;; milliseconds.
+ ;;
+ ;; Without this, once the pool hits maxPoolSize every additional query blocks forever waiting for a free
+ ;; connection, so a backlog can grow without bound under load. With it, an over-loaded instance sheds load: the
+ ;; checkout fails fast and the QP turns the resulting timeout into an HTTP 429 (see
+ ;; [[metabase.driver.sql-jdbc.execute/do-with-resolved-connection]]).
+ "checkoutTimeout" (driver.settings/jdbc-data-warehouse-connection-pool-checkout-timeout-ms)
;; [From dox] If true, an operation will be performed at every connection checkout to verify that the connection is
;; valid. [...] ;; Testing Connections in checkout is the simplest and most reliable form of Connection testing,
;; but for better performance, consider verifying connections periodically using `idleConnectionTestPeriod`. [...]
diff --git a/src/metabase/driver/sql_jdbc/execute.clj b/src/metabase/driver/sql_jdbc/execute.clj
index 5bb5f9a20b5..d4642fc769c 100644
--- a/src/metabase/driver/sql_jdbc/execute.clj
+++ b/src/metabase/driver/sql_jdbc/execute.clj
@@ -30,6 +30,7 @@
[metabase.util.performance :as perf :refer [empty? get-in mapv]]
[potemkin :as p])
(:import
+ (com.mchange.v2.resourcepool TimeoutException)
(java.sql Connection JDBCType PreparedStatement ResultSet ResultSetMetaData SQLFeatureNotSupportedException Statement Types)
(java.time Instant LocalDate LocalDateTime LocalTime OffsetDateTime OffsetTime ZonedDateTime)
(java.util.concurrent Executors)
@@ -320,6 +321,17 @@
[]
(pos? *connection-recursion-depth*))
+(defn- connection-checkout-timeout?
+ "True if `e` (or anything in its cause chain) is a c3p0 pool-checkout timeout, i.e. the data-warehouse connection
+ pool was exhausted and the wait exceeded [[driver.settings/jdbc-data-warehouse-connection-pool-checkout-timeout-ms]].
+ c3p0 signals this by throwing a `SQLException` caused by a `com.mchange.v2.resourcepool.TimeoutException`."
+ [^Throwable e]
+ (loop [cause e]
+ (cond
+ (nil? cause) false
+ (instance? TimeoutException cause) true
+ :else (recur (.getCause cause)))))
+
(mu/defn do-with-resolved-connection
"Execute
@@ -341,10 +353,15 @@
(try
(.getConnection conn-data-source)
(catch Throwable e
- (throw (ex-info (tru "Unable to connect to the database: {0}" (ex-message e))
- {:type driver-api/qp.error-type.unable-to-acquire-connection
- :driver driver}
- e))))))]
+ (let [timed-out? (connection-checkout-timeout? e)]
+ (throw (ex-info (if timed-out?
+ (tru "Too many queries are running. Please try again in a moment.")
+ (tru "Unable to connect to the database: {0}" (ex-message e)))
+ {:type (if timed-out?
+ driver-api/qp.error-type.timed-out-acquiring-connection
+ driver-api/qp.error-type.unable-to-acquire-connection)
+ :driver driver}
+ e)))))))]
(if (:keep-open? options)
(f (get-conn))
(with-open [conn ^Connection (get-conn)]
diff --git a/src/metabase/driver_api/core.clj b/src/metabase/driver_api/core.clj
index 8c80e88531a..b3d1569b140 100644
--- a/src/metabase/driver_api/core.clj
+++ b/src/metabase/driver_api/core.clj
@@ -199,6 +199,7 @@
(p/import-def qp.error-type/invalid-query qp.error-type.invalid-query)
(p/import-def qp.error-type/missing-required-parameter qp.error-type.missing-required-parameter)
(p/import-def qp.error-type/qp qp.error-type.qp)
+(p/import-def qp.error-type/timed-out-acquiring-connection qp.error-type.timed-out-acquiring-connection)
(p/import-def qp.error-type/unable-to-acquire-connection qp.error-type.unable-to-acquire-connection)
(p/import-def qp.error-type/unsupported-feature qp.error-type.unsupported-feature)
diff --git a/src/metabase/query_processor/error_type.clj b/src/metabase/query_processor/error_type.clj
index ca02647042d..3d0fa1c9bbd 100644
--- a/src/metabase/query_processor/error_type.clj
+++ b/src/metabase/query_processor/error_type.clj
@@ -114,6 +114,19 @@
:parent client
:show-in-embeds? true)
+(deferror timed-out-acquiring-connection
+ "We were unable to acquire a connection to the query's database before the checkout timeout elapsed because the
+ connection pool is saturated. Equivalent of an HTTP 503 (Service Unavailable); this is a transient condition the
+ client may retry. Unlike `unable-to-acquire-connection` it is not a `client` error (the query itself is fine), and
+ unlike a generic `server` error it is expected under load rather than a bug."
+ :parent :error
+ :show-in-embeds? true)
+
+(defn timed-out-acquiring-connection?
+ "Is `error-type` a connection-pool-saturation error, the equivalent of an HTTP 503 status code?"
+ [error-type]
+ (isa? hierarchy error-type timed-out-acquiring-connection))
+
;;;; ### Server-Side Errors
(deferror server
diff --git a/src/metabase/query_processor/streaming.clj b/src/metabase/query_processor/streaming.clj
index 6a46b7a6a9f..4c91e6f5553 100644
--- a/src/metabase/query_processor/streaming.clj
+++ b/src/metabase/query_processor/streaming.clj
@@ -223,6 +223,9 @@
(:status-code err) (:status-code err)
;; If the error is setting its own status code use that
(-> err :ex-data :status-code) (-> err :ex-data :status-code)
+ ;; If a resource is saturated (e.g. the connection pool is exhausted) return 503 so clients retry/back off
+ (-> err :error_type qp.error-type/timed-out-acquiring-connection?)
+ 503
;; If this is a permission error return 403
(-> err :error_type qp.error-type/permission-error?)
403
diff --git a/test/metabase/driver/sql_jdbc/connection_test.clj b/test/metabase/driver/sql_jdbc/connection_test.clj
index 581c8668b76..90bc8250b15 100644
--- a/test/metabase/driver/sql_jdbc/connection_test.clj
+++ b/test/metabase/driver/sql_jdbc/connection_test.clj
@@ -396,6 +396,20 @@
(is (= 20
(sql-jdbc.conn/jdbc-data-warehouse-unreturned-connection-timeout-seconds))))))
+(deftest ^:parallel include-checkout-timeout-test
+ (testing "We should be setting checkoutTimeout so a saturated pool fails fast instead of queueing forever"
+ (is (=? {"checkoutTimeout" integer?}
+ (sql-jdbc.conn/data-warehouse-connection-pool-properties :h2 (mt/db))))))
+
+(deftest checkout-timeout-env-var-test
+ (testing "We should be able to set jdbc-data-warehouse-connection-pool-checkout-timeout-ms via env var"
+ (mt/with-temp-env-var-value! [mb-jdbc-data-warehouse-connection-pool-checkout-timeout-ms "5000"]
+ (is (= 5000
+ (driver.settings/jdbc-data-warehouse-connection-pool-checkout-timeout-ms)))
+ (is (= 5000
+ (get (sql-jdbc.conn/data-warehouse-connection-pool-properties :h2 (mt/db))
+ "checkoutTimeout"))))))
+
(deftest ^:parallel include-debug-unreturned-connection-stack-traces-test
(testing "We should be setting debugUnreturnedConnectionStackTraces (#47981)"
(is (=? {"debugUnreturnedConnectionStackTraces" boolean?}
diff --git a/test/metabase/driver/sql_jdbc/execute_test.clj b/test/metabase/driver/sql_jdbc/execute_test.clj
index 8affd02cde8..c7d10238299 100644
--- a/test/metabase/driver/sql_jdbc/execute_test.clj
+++ b/test/metabase/driver/sql_jdbc/execute_test.clj
@@ -232,3 +232,23 @@
:native {:query "SELECT 1"}}
response (mt/user-http-request :crowberto :post 400 "dataset" query)]
(is (= "unable-to-acquire-connection" (:error_type response))))))))
+
+(deftest connection-pool-checkout-timeout-returns-503-test
+ (testing "A c3p0 checkout timeout (saturated pool) surfaces to the frontend as a retriable HTTP 503"
+ (mt/test-drivers (mt/normal-driver-select {:+parent :sql-jdbc})
+ #_{:clj-kondo/ignore [:discouraged-var]}
+ (mt/with-temp [:model/Database tmp-db {:details (tx/bad-connection-details driver/*driver*)
+ :engine driver/*driver*}]
+ (with-redefs [h2/check-read-only-statements (fn [_query] nil)
+ sql-jdbc.execute/do-with-resolved-connection-data-source
+ (fn [_driver _db-or-id-or-spec _options]
+ (reify javax.sql.DataSource
+ (getConnection [_]
+ (throw (java.sql.SQLException.
+ "An attempt by a client to checkout a Connection has timed out."
+ (com.mchange.v2.resourcepool.TimeoutException. "timed out"))))))]
+ (let [query {:database (:id tmp-db)
+ :type :native
+ :native {:query "SELECT 1"}}
+ response (mt/user-http-request :crowberto :post 503 "dataset" query)]
+ (is (= "timed-out-acquiring-connection" (:error_type response)))))))))