Service API fails all requests with QueuePool timeout once concurrent requests reach the database pool capacity
Self Checks
- [x] I have read the Contributing Guide and Language Policy.
- [x] This is only for bug report, if you would like to ask a question, please head to Discussions.
- [x] I have searched for existing issues search for existing issues, including closed ones.
- [x] I confirm that I am using English to submit this report, otherwise it will be closed.
- [x] 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :)
- [x] Please do not modify this template :) and fill in all the required fields.
Dify version
1.19.0 (the affected code is unchanged on main at 4833948da)
Cloud or Self Hosted
Self Hosted (Docker)
Steps to reproduce
- Start Dify 1.19.0 with Docker Compose. Keep the default database pool (
SQLALCHEMY_POOL_SIZE=30,SQLALCHEMY_MAX_OVERFLOW=10) and let the API accept more concurrent connections than the pool can serve:SERVER_WORKER_CONNECTIONS=1000. To keep the worker from being the bottleneck, setCELERY_WORKER_AMOUNT=100. - Create a Workflow app: Start → HTTP Request (GET an endpoint that answers after about 2 seconds) → End. Publish it and create an API key.
- Send 100 requests at the same time:
import json, threading, urllib.request
from concurrent.futures import ThreadPoolExecutor
URL, KEY, N = "http://localhost/v1/workflows/run", "app-...", 100
gate = threading.Event()
def run(i):
body = json.dumps({"inputs": {}, "response_mode": "streaming", "user": f"u{i}"}).encode()
req = urllib.request.Request(URL, data=body, headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"})
gate.wait()
try:
with urllib.request.urlopen(req, timeout=300) as r:
return r.read()[-200:]
except Exception as e:
return e
with ThreadPoolExecutor(N) as ex:
futures = [ex.submit(run, i) for i in range(N)]
gate.set()
print(sum(isinstance(f.result(), Exception) for f in futures), "failed of", N)
✔️ Expected Behavior
Requests beyond the pool capacity wait for a connection and then complete. Throughput is bounded by the pool, but requests do not fail.
❌ Actual Behavior
The API stops making progress for 30 seconds and then answers most or all requests with HTTP 500. CPU is idle on every container while it happens.
Results on one machine (API: one gevent process; a round is N requests sent at once):
| Setup | Round results (succeeded / sent) |
|---|---|
| 1.19.0, pool 30+10, 100 concurrent | 18/100, 0/100, 21/100, 100/100 |
| 1.19.0, pool 30+10, 60 concurrent | 41/60, 60/60 |
1.19.0, SQLALCHEMY_POOL_SIZE=120, 100 concurrent |
100/100 (14.8 s, about 150 PostgreSQL connections in use) |
| 1.19.0 with the fix below, pool 30+10, 100 concurrent | 100/100, 100/100, 100/100 (9.0–15.3 s) |
| 1.19.0 with the fix below, pool 30+10, 200 concurrent | 200/200 (14.1 s, about 60 PostgreSQL connections in use) |
It is timing dependent, which is why one unpatched round passed.
API log of a round where all 100 failed:
sqlalchemy.exc.TimeoutError: QueuePool limit of size 30 overflow 10 reached, connection timed out, timeout 30.00
60 of the 100 requests were waiting here:
File "/app/api/controllers/service_api/wraps.py", line 140, in decorated_view
File "/app/api/services/app_service.py", line 314, in get_app_by_id
and 40 (exactly the pool capacity) here:
File "/app/api/controllers/service_api/wraps.py", line 160, in decorated_view
File "/app/api/controllers/service_api/wraps.py", line 212, in resolve_service_api_end_user
File "/app/api/repositories/app_scoped_end_user_repository.py", line 87, in find_by_session
Cause. validate_app_token loads the app and workspace through the request-scoped db.session (lines 140 and 150), which leaves that session inside a transaction holding one pooled connection. resolve_service_api_end_user then opens a second session through the repository's session factory, and the @with_session handler opens a third. So every in-flight request needs two connections at once. When the number of in-flight requests reaches the pool capacity, every connection is held by a request that is waiting for a second one, and all of them time out together.
Two side effects of the same hold:
- The request-scoped session keeps its connection until the response ends, so every open stream pins one connection for its whole duration (about 150 connections for 100 streams in the table above).
- It cannot happen with the default
SERVER_WORKER_CONNECTIONS=10, because 10 is below the pool capacity. It appears as soon as an operator raises API concurrency to the pool capacity or above, which is the first thing people do to serve more users.
Fix I verified. End the admission read transaction before end-user provisioning and before the handler runs, keeping the loaded rows attached and unexpired. I will open a pull request with this change and regression tests.
The dataset Service API has the same defect. validate_dataset_token queries the request-scoped db.session (get_active_key_scope, the dataset lookup, the workspace owner lookup) and leaves it inside a transaction; the @with_session dataset handlers then open a second session.
Same setup as above (1.19.0, SERVER_WORKER_CONNECTIONS=1000, default pool 30 + 10), GET /v1/datasets/tags with a dataset API key, fresh containers:
| Concurrent requests | 1.19.0 | With #46244 |
|---|---|---|
| 60 | 60/60 in 0.25 s | 60/60 in 0.23 s |
| 100 | 0/100, all HTTP 500 after 30 s | 100/100 in 0.37 s |
| 200 | not run | 200/200 in 0.6 s |
The 100 failures split the same way: requests waiting at controllers/service_api/wraps.py:380 (get_active_key_scope, first connection) and requests waiting for their second connection inside the handler session (controllers/common/session.py:59). #46244 now covers this decorator as well.