Skip to content

Openverse is a search engine for openly-licensed media. This monorepo includes all application code.

Size the API's DB connection pool for request concurrency and shorten ES timeouts (#5674)

Dhruv Bhanushali6fa04650d4df
diff --git a/api/conf/settings/databases.py b/api/conf/settings/databases.py
index a48fdcb97..f93c498e7 100644
--- a/api/conf/settings/databases.py
+++ b/api/conf/settings/databases.py
@@ -19,7 +19,23 @@ DATABASES = {
"application_name": config(
"DJANGO_DATABASE_APPLICATION_NAME", default="openverse-api"
),
- "pool": True,
+ # Every request holds its pooled connection for its whole lifetime,
+ # including slow outbound calls (ES, dead-link checks, thumbnails),
+ # so the pool must be sized for request concurrency rather than
+ # DB concurrency. psycopg's defaults (max_size = min_size = 4,
+ # 30 s wait, unbounded queue) stalled entire tasks, health check
+ # included, whenever ES slowed down.
+ "pool": {
+ "min_size": config(
+ "DJANGO_DATABASE_POOL_MIN_SIZE", default=4, cast=int
+ ),
+ "max_size": config(
+ "DJANGO_DATABASE_POOL_MAX_SIZE", default=32, cast=int
+ ),
+ "timeout": config(
+ "DJANGO_DATABASE_POOL_TIMEOUT", default=10, cast=float
+ ),
+ },
},
}
}
diff --git a/api/conf/settings/elasticsearch.py b/api/conf/settings/elasticsearch.py
index 19aba5376..974af1abb 100644
--- a/api/conf/settings/elasticsearch.py
+++ b/api/conf/settings/elasticsearch.py
@@ -22,11 +22,15 @@ def _elasticsearch_connect() -> tuple[Elasticsearch, str]:
_es = Elasticsearch(
es_endpoint,
- # TODO: Return to default timeout of 10s and 1 retry once
- # TODO: Elasticsearch response time has been stabilized
- request_timeout=12,
- max_retries=3,
- retry_on_timeout=True,
+ # A search holds a pooled DB connection for as long as ES takes to
+ # answer, so a generous timeout with retries (previously 12 s × 4
+ # attempts) lets a slow cluster exhaust the pool and take the whole
+ # task down. Fail the one slow request instead.
+ request_timeout=config("ELASTICSEARCH_REQUEST_TIMEOUT", default=8, cast=float),
+ max_retries=config("ELASTICSEARCH_MAX_RETRIES", default=1, cast=int),
+ retry_on_timeout=config(
+ "ELASTICSEARCH_RETRY_ON_TIMEOUT", default=False, cast=bool
+ ),
)
_es.info()
_es.cluster.health(wait_for_status="yellow")
diff --git a/api/env.template b/api/env.template
index 0c14ebb34..906541ed2 100644
--- a/api/env.template
+++ b/api/env.template
@@ -28,6 +28,9 @@ ENVIRONMENT=local
#DJANGO_DATABASE_NAME=openledger
#DJANGO_DATABASE_APPLICATION_NAME=openverse-api
#DJANGO_DATABASE_LOGGING=False
+#DJANGO_DATABASE_POOL_MIN_SIZE=4
+#DJANGO_DATABASE_POOL_MAX_SIZE=32
+#DJANGO_DATABASE_POOL_TIMEOUT=10
SEMANTIC_VERSION=1.0.0
@@ -35,6 +38,9 @@ SEMANTIC_VERSION=1.0.0
#ELASTICSEARCH_URL=es
#ELASTICSEARCH_PORT=9200
#ELASTICSEARCH_AWS_REGION=us-east-1
+#ELASTICSEARCH_REQUEST_TIMEOUT=8
+#ELASTICSEARCH_MAX_RETRIES=1
+#ELASTICSEARCH_RETRY_ON_TIMEOUT=False
#IMAGE_INDEX_NAME=image
#AUDIO_INDEX_NAME=audio