Skip to content

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

jdbc-data-warehouse-connection-pool-max-pending-checkouts (#77004)

Alexander Polyankind141f2f00e0f
diff --git a/src/metabase/driver/settings.clj b/src/metabase/driver/settings.clj
index 27126e9260a..b27bfddcc38 100644
--- a/src/metabase/driver/settings.clj
+++ b/src/metabase/driver/settings.clj
@@ -142,6 +142,23 @@
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.")
+(defsetting jdbc-data-warehouse-connection-pool-max-pending-checkouts
+ "Maximum number of queries allowed to be waiting for a free data-warehouse connection at once, once the c3p0 pool has
+ hit [[jdbc-data-warehouse-max-connection-pool-size]]. When this many queries are already queued waiting for a
+ connection, further queries fail fast instead of joining the queue, which the query processor surfaces to the
+ frontend as an HTTP 503 (Service Unavailable). `0` (the default) lets the queue grow without bound (the old
+ behavior). Complements [[jdbc-data-warehouse-connection-pool-checkout-timeout-ms]], which bounds how long each query
+ waits; this bounds how many can wait at the same time."
+ :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 number of queries that may be waiting at the same time before further queries fail immediately with a
+ \"service unavailable\" (HTTP 503) error instead of joining the queue. Raise it to tolerate deeper bursts; set it to
+ `0` to allow an unbounded queue.")
+
(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 fd9d7b19299..5bce228a9b5 100644
--- a/src/metabase/driver/sql_jdbc/connection.clj
+++ b/src/metabase/driver/sql_jdbc/connection.clj
@@ -112,8 +112,9 @@
;;
;; 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]]).
+ ;; checkout fails fast and the QP turns the resulting timeout into an HTTP 503 (see
+ ;; [[metabase.driver.sql-jdbc.execute/do-with-resolved-connection]]). The number of queries allowed to wait at once
+ ;; is separately bounded by [[driver.settings/jdbc-data-warehouse-connection-pool-max-pending-checkouts]].
"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,
diff --git a/src/metabase/driver/sql_jdbc/execute.clj b/src/metabase/driver/sql_jdbc/execute.clj
index d4642fc769c..5837915d16e 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.c3p0 PooledDataSource)
(com.mchange.v2.resourcepool TimeoutException)
(java.sql Connection JDBCType PreparedStatement ResultSet ResultSetMetaData SQLFeatureNotSupportedException Statement Types)
(java.time Instant LocalDate LocalDateTime LocalTime OffsetDateTime OffsetTime ZonedDateTime)
@@ -332,6 +333,22 @@
(instance? TimeoutException cause) true
:else (recur (.getCause cause)))))
+(defn- checkout-queue-full?
+ "True if `data-source` already has at least
+ [[driver.settings/jdbc-data-warehouse-connection-pool-max-pending-checkouts]] queries waiting for a free connection.
+ Used to shed load: rather than letting the checkout queue grow without bound when the pool is saturated, additional
+ queries are rejected immediately. A limit of `0` (the default) disables the check. Only c3p0 `PooledDataSource`s
+ expose the waiting-thread count; any other data source is never considered full."
+ [data-source]
+ (let [max-pending (driver.settings/jdbc-data-warehouse-connection-pool-max-pending-checkouts)]
+ (and (pos? max-pending)
+ (instance? PooledDataSource data-source)
+ (try
+ (>= (.getNumThreadsAwaitingCheckoutDefaultUser ^PooledDataSource data-source) max-pending)
+ (catch Throwable _
+ ;; if we can't read the stat for some reason, fail open rather than blocking queries
+ false)))))
+
(mu/defn do-with-resolved-connection
"Execute
@@ -350,6 +367,10 @@
(f conn)
(let [get-conn (^:once fn* []
(let [conn-data-source (do-with-resolved-connection-data-source driver db-or-id-or-spec options)]
+ (when (checkout-queue-full? conn-data-source)
+ (throw (ex-info (tru "Too many queries are running. Please try again in a moment.")
+ {:type driver-api/qp.error-type.connection-pool-checkout-queue-full
+ :driver driver})))
(try
(.getConnection conn-data-source)
(catch Throwable e
@@ -358,7 +379,7 @@
(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.connection-pool-checkout-timeout
driver-api/qp.error-type.unable-to-acquire-connection)
:driver driver}
e)))))))]
diff --git a/src/metabase/driver_api/core.clj b/src/metabase/driver_api/core.clj
index b3d1569b140..ef16fd0085b 100644
--- a/src/metabase/driver_api/core.clj
+++ b/src/metabase/driver_api/core.clj
@@ -193,13 +193,14 @@
(p/import-fn lib/unique-name-generator-with-options unique-name-generator)
+(p/import-def qp.error-type/connection-pool-checkout-queue-full qp.error-type.connection-pool-checkout-queue-full)
+(p/import-def qp.error-type/connection-pool-checkout-timeout qp.error-type.connection-pool-checkout-timeout)
(p/import-def qp.error-type/db qp.error-type.db)
(p/import-def qp.error-type/driver qp.error-type.driver)
(p/import-def qp.error-type/invalid-parameter qp.error-type.invalid-parameter)
(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 3d0fa1c9bbd..56bc6b04a49 100644
--- a/src/metabase/query_processor/error_type.clj
+++ b/src/metabase/query_processor/error_type.clj
@@ -114,18 +114,36 @@
: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."
+;;;; #### Connection-Pool Saturation Errors
+;;;;
+;;;; A database's connection pool is momentarily overloaded. These are transient and retriable — the query itself is
+;;;; fine — so the query processor maps them to an HTTP 503 (Service Unavailable), not a 4xx. Contrast with
+;;;; `unable-to-acquire-connection`, a `client` error meaning we cannot connect to the database at all.
+
+(deferror connection-pool-saturated
+ "Ancestor type for the transient errors raised when a database's connection pool is saturated — every connection is
+ in use and the pool has hit `jdbc-data-warehouse-max-connection-pool-size`. Equivalent of an HTTP 503 (Service
+ Unavailable); the client may retry. Not thrown directly; see the children [[connection-pool-checkout-timeout]] and
+ [[connection-pool-checkout-queue-full]]."
: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?"
+(deferror connection-pool-checkout-timeout
+ "A query waited for a free connection to its database but gave up once the wait exceeded
+ `jdbc-data-warehouse-connection-pool-checkout-timeout-ms`."
+ :parent connection-pool-saturated)
+
+(deferror connection-pool-checkout-queue-full
+ "A query was rejected immediately, without waiting, because the number of queries already waiting for a free
+ connection to its database had reached `jdbc-data-warehouse-connection-pool-max-pending-checkouts`."
+ :parent connection-pool-saturated)
+
+(defn connection-pool-saturated?
+ "Is `error-type` a connection-pool-saturation error, the equivalent of an HTTP 503 status code? True for both a
+ checkout timeout ([[connection-pool-checkout-timeout]]) and a full checkout queue
+ ([[connection-pool-checkout-queue-full]])."
[error-type]
- (isa? hierarchy error-type timed-out-acquiring-connection))
+ (isa? hierarchy error-type connection-pool-saturated))
;;;; ### Server-Side Errors
diff --git a/src/metabase/query_processor/streaming.clj b/src/metabase/query_processor/streaming.clj
index 4c91e6f5553..f139f22f8c9 100644
--- a/src/metabase/query_processor/streaming.clj
+++ b/src/metabase/query_processor/streaming.clj
@@ -223,8 +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?)
+ ;; If the connection pool is saturated (checkout timed out, or the checkout queue is full) return 503 so clients
+ ;; retry/back off
+ (-> err :error_type qp.error-type/connection-pool-saturated?)
503
;; If this is a permission error return 403
(-> err :error_type qp.error-type/permission-error?)
diff --git a/test/metabase/driver/sql_jdbc/connection_test.clj b/test/metabase/driver/sql_jdbc/connection_test.clj
index 90bc8250b15..e5710b4ec3f 100644
--- a/test/metabase/driver/sql_jdbc/connection_test.clj
+++ b/test/metabase/driver/sql_jdbc/connection_test.clj
@@ -410,6 +410,12 @@
(get (sql-jdbc.conn/data-warehouse-connection-pool-properties :h2 (mt/db))
"checkoutTimeout"))))))
+(deftest max-pending-checkouts-env-var-test
+ (testing "We should be able to set jdbc-data-warehouse-connection-pool-max-pending-checkouts via env var"
+ (mt/with-temp-env-var-value! [mb-jdbc-data-warehouse-connection-pool-max-pending-checkouts "25"]
+ (is (= 25
+ (driver.settings/jdbc-data-warehouse-connection-pool-max-pending-checkouts))))))
+
(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 c7d10238299..b010a4b5810 100644
--- a/test/metabase/driver/sql_jdbc/execute_test.clj
+++ b/test/metabase/driver/sql_jdbc/execute_test.clj
@@ -251,4 +251,40 @@
:type :native
:native {:query "SELECT 1"}}
response (mt/user-http-request :crowberto :post 503 "dataset" query)]
- (is (= "timed-out-acquiring-connection" (:error_type response)))))))))
+ (is (= "connection-pool-checkout-timeout" (:error_type response)))))))))
+
+(deftest checkout-queue-full?-test
+ (let [full? #'sql-jdbc.execute/checkout-queue-full?]
+ (testing "a limit of 0 (the default) disables the check even when many queries are waiting"
+ (mt/with-temporary-setting-values [jdbc-data-warehouse-connection-pool-max-pending-checkouts 0]
+ (is (false? (full? (reify com.mchange.v2.c3p0.PooledDataSource
+ (getNumThreadsAwaitingCheckoutDefaultUser [_] 100)))))))
+ (testing "non-pooled data sources are never considered full"
+ (mt/with-temporary-setting-values [jdbc-data-warehouse-connection-pool-max-pending-checkouts 1]
+ (is (false? (full? (reify javax.sql.DataSource
+ (getConnection [_] nil)))))))
+ (testing "full only once the waiting count reaches the limit"
+ (mt/with-temporary-setting-values [jdbc-data-warehouse-connection-pool-max-pending-checkouts 3]
+ (is (false? (full? (reify com.mchange.v2.c3p0.PooledDataSource
+ (getNumThreadsAwaitingCheckoutDefaultUser [_] 2)))))
+ (is (true? (full? (reify com.mchange.v2.c3p0.PooledDataSource
+ (getNumThreadsAwaitingCheckoutDefaultUser [_] 3)))))))))
+
+(deftest connection-pool-full-checkout-queue-returns-503-test
+ (testing "When the checkout queue is full, additional queries fail fast with 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*}]
+ (mt/with-temporary-setting-values [jdbc-data-warehouse-connection-pool-max-pending-checkouts 1]
+ (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]
+ ;; a pool that already has more queries waiting than the configured max
+ (reify com.mchange.v2.c3p0.PooledDataSource
+ (getNumThreadsAwaitingCheckoutDefaultUser [_] 5)))]
+ (let [query {:database (:id tmp-db)
+ :type :native
+ :native {:query "SELECT 1"}}
+ response (mt/user-http-request :crowberto :post 503 "dataset" query)]
+ (is (= "connection-pool-checkout-queue-full" (:error_type response))))))))))