Skip to content

Commit 6aae500

Browse files
committed
feat: configure the connection pool and cap requests in flight (#146)
1 parent 3d0d70c commit 6aae500

8 files changed

Lines changed: 407 additions & 18 deletions

File tree

‎src/typesense/async_/api_call.py‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737

3838
import httpx
3939

40+
from typesense.concurrency_limit import AsyncConcurrencyLimit
4041
from typesense.configuration import Configuration, Node
4142
from typesense.exceptions import (
4243
HTTPStatus0Error,
@@ -174,7 +175,17 @@ def __init__(self, config: Configuration):
174175
self.node_manager = NodeManager(config)
175176
self.request_handler = RequestHandler(config)
176177
self._client = httpx.AsyncClient(
177-
timeout=config.connection_timeout_seconds,
178+
timeout=httpx.Timeout(
179+
config.connection_timeout_seconds,
180+
pool=config.pool_timeout_seconds,
181+
),
182+
limits=httpx.Limits(
183+
max_connections=config.max_connections,
184+
max_keepalive_connections=config.max_keepalive_connections,
185+
),
186+
)
187+
self._concurrency_limit = AsyncConcurrencyLimit(
188+
config.max_concurrent_requests,
178189
)
179190

180191
async def __aenter__(self) -> "AsyncApiCall":
@@ -519,14 +530,15 @@ async def _make_request_and_process_response(
519530
**kwargs: typing.Unpack[SessionFunctionKwargs[TParams, TBody]],
520531
) -> typing.Union[TEntityDict, str]:
521532
"""Make the async API request to `node` and process the response."""
522-
request_response = await self.request_handler.make_request(
523-
method=method,
524-
url=url,
525-
as_json=as_json,
526-
entity_type=entity_type,
527-
client=self._client,
528-
**kwargs,
529-
)
533+
async with self._concurrency_limit:
534+
request_response = await self.request_handler.make_request(
535+
method=method,
536+
url=url,
537+
as_json=as_json,
538+
entity_type=entity_type,
539+
client=self._client,
540+
**kwargs,
541+
)
530542
self.node_manager.set_node_health(node, is_healthy=True)
531543
return (
532544
typing.cast(TEntityDict, request_response)

‎src/typesense/concurrency_limit.py‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
"""
2+
Optional caps on the number of requests a client sends at once.
3+
4+
``AsyncConcurrencyLimit`` is used by the async client and ``ConcurrencyLimit`` by the
5+
sync client (``utils/run-unasync.py`` maps one name to the other). Both are no-ops
6+
when ``max_concurrent_requests`` is ``None``.
7+
8+
Keeping the cap below the httpx pool's ``max_connections`` means requests queue here
9+
instead of in the pool, so a burst of slow requests cannot exhaust the pool and
10+
raise ``httpx.PoolTimeout``.
11+
"""
12+
13+
import asyncio
14+
import sys
15+
import threading
16+
from types import TracebackType
17+
18+
if sys.version_info >= (3, 11):
19+
import typing
20+
else:
21+
import typing_extensions as typing
22+
23+
24+
class AsyncConcurrencyLimit:
25+
"""Async context manager that holds a slot for the duration of a request."""
26+
27+
def __init__(self, max_concurrent_requests: typing.Optional[int]) -> None:
28+
"""
29+
Initialize the limit.
30+
31+
Args:
32+
max_concurrent_requests (Optional[int]): The maximum number of requests
33+
in flight at once, or ``None`` for no limit.
34+
"""
35+
self._max_concurrent_requests = max_concurrent_requests
36+
# Created on first use, inside the running event loop. On Python < 3.10 a
37+
# semaphore binds to the loop that is current when it is constructed.
38+
self._semaphore: typing.Optional[asyncio.Semaphore] = None
39+
40+
async def __aenter__(self) -> None:
41+
"""Wait for a free slot."""
42+
if self._max_concurrent_requests is None:
43+
return
44+
if self._semaphore is None:
45+
self._semaphore = asyncio.Semaphore(self._max_concurrent_requests)
46+
await self._semaphore.acquire()
47+
48+
async def __aexit__(
49+
self,
50+
exc_type: typing.Optional[typing.Type[BaseException]],
51+
exc_val: typing.Optional[BaseException],
52+
exc_tb: typing.Optional[TracebackType],
53+
) -> None:
54+
"""Release the slot."""
55+
if self._semaphore is not None:
56+
self._semaphore.release()
57+
58+
59+
class ConcurrencyLimit:
60+
"""Context manager that holds a slot for the duration of a request."""
61+
62+
def __init__(self, max_concurrent_requests: typing.Optional[int]) -> None:
63+
"""
64+
Initialize the limit.
65+
66+
Args:
67+
max_concurrent_requests (Optional[int]): The maximum number of requests
68+
in flight at once, or ``None`` for no limit.
69+
"""
70+
self._semaphore: typing.Optional[threading.Semaphore] = (
71+
None
72+
if max_concurrent_requests is None
73+
else threading.Semaphore(max_concurrent_requests)
74+
)
75+
76+
def __enter__(self) -> None:
77+
"""Wait for a free slot."""
78+
if self._semaphore is not None:
79+
self._semaphore.acquire()
80+
81+
def __exit__(
82+
self,
83+
exc_type: typing.Optional[typing.Type[BaseException]],
84+
exc_val: typing.Optional[BaseException],
85+
exc_tb: typing.Optional[TracebackType],
86+
) -> None:
87+
"""Release the slot."""
88+
if self._semaphore is not None:
89+
self._semaphore.release()

‎src/typesense/configuration.py‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,23 @@ class ConfigDict(typing.TypedDict):
8282
connection_timeout_seconds (float): The connection timeout in seconds.
8383
8484
suppress_deprecation_warnings (bool): Whether to suppress deprecation warnings.
85+
86+
pool_timeout_seconds (float): How long a request waits for a free connection
87+
in the pool before raising ``httpx.PoolTimeout``. Defaults to
88+
``connection_timeout_seconds``. Setting it lower than
89+
``connection_timeout_seconds`` makes the httpcore connection leak
90+
(encode/httpcore#1093) more likely under load.
91+
92+
max_connections (int): The maximum number of connections in the pool.
93+
Defaults to 100.
94+
95+
max_keepalive_connections (int): The maximum number of idle connections
96+
kept alive in the pool. Defaults to 20.
97+
98+
max_concurrent_requests (int): The maximum number of requests in flight at
99+
once; further requests wait for a slot. Keep it below
100+
``max_connections`` so a burst of slow requests cannot exhaust the pool.
101+
Defaults to no limit.
85102
"""
86103

87104
nodes: typing.List[typing.Union[str, NodeConfigDict]]
@@ -100,6 +117,10 @@ class ConfigDict(typing.TypedDict):
100117
] # deprecated
101118
connection_timeout_seconds: typing.NotRequired[float]
102119
suppress_deprecation_warnings: typing.NotRequired[bool]
120+
pool_timeout_seconds: typing.NotRequired[float]
121+
max_connections: typing.NotRequired[int]
122+
max_keepalive_connections: typing.NotRequired[int]
123+
max_concurrent_requests: typing.NotRequired[int]
103124

104125

105126
class Node:
@@ -188,6 +209,10 @@ class Configuration:
188209
retry_interval_seconds (float): The interval in seconds between retries.
189210
healthcheck_interval_seconds (int): The interval in seconds between health checks.
190211
verify (bool): Whether to verify the SSL certificate.
212+
pool_timeout_seconds (float): How long to wait for a free pooled connection.
213+
max_connections (int): The maximum number of connections in the pool.
214+
max_keepalive_connections (int): The maximum number of idle pooled connections.
215+
max_concurrent_requests (int | None): The maximum number of requests in flight.
191216
"""
192217

193218
def __init__(
@@ -232,6 +257,18 @@ def __init__(
232257
self.suppress_deprecation_warnings = config_dict.get(
233258
"suppress_deprecation_warnings", False
234259
)
260+
self.pool_timeout_seconds = config_dict.get(
261+
"pool_timeout_seconds",
262+
self.connection_timeout_seconds,
263+
)
264+
self.max_connections = config_dict.get("max_connections", 100)
265+
self.max_keepalive_connections = config_dict.get(
266+
"max_keepalive_connections",
267+
20,
268+
)
269+
self.max_concurrent_requests: typing.Optional[int] = config_dict.get(
270+
"max_concurrent_requests",
271+
)
235272

236273
def _handle_nearest_node(
237274
self,
@@ -295,6 +332,32 @@ def validate_config_dict(config_dict: ConfigDict) -> None:
295332
if nearest_node:
296333
ConfigurationValidations.validate_nearest_node(nearest_node)
297334

335+
ConfigurationValidations.validate_connection_pool(config_dict)
336+
337+
@staticmethod
338+
def validate_connection_pool(config_dict: ConfigDict) -> None:
339+
"""
340+
Validate the connection pool and concurrency settings.
341+
342+
Args:
343+
config_dict (ConfigDict): The configuration dictionary to validate.
344+
345+
Raises:
346+
ConfigError: If a pool or concurrency setting is out of range.
347+
"""
348+
positive_settings: typing.Dict[str, typing.Optional[float]] = {
349+
"pool_timeout_seconds": config_dict.get("pool_timeout_seconds"),
350+
"max_connections": config_dict.get("max_connections"),
351+
"max_concurrent_requests": config_dict.get("max_concurrent_requests"),
352+
}
353+
for key, config_value in positive_settings.items():
354+
if config_value is not None and config_value <= 0:
355+
raise ConfigError(f"`{key}` must be greater than 0.")
356+
357+
max_keepalive_connections = config_dict.get("max_keepalive_connections")
358+
if max_keepalive_connections is not None and max_keepalive_connections < 0:
359+
raise ConfigError("`max_keepalive_connections` must not be negative.")
360+
298361
@staticmethod
299362
def validate_required_config_fields(config_dict: ConfigDict) -> None:
300363
"""

‎src/typesense/sync/api_call.py‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737

3838
import httpx
3939

40+
from typesense.concurrency_limit import ConcurrencyLimit
4041
from typesense.configuration import Configuration, Node
4142
from typesense.exceptions import (
4243
HTTPStatus0Error,
@@ -174,7 +175,17 @@ def __init__(self, config: Configuration):
174175
self.node_manager = NodeManager(config)
175176
self.request_handler = RequestHandler(config)
176177
self._client = httpx.Client(
177-
timeout=config.connection_timeout_seconds,
178+
timeout=httpx.Timeout(
179+
config.connection_timeout_seconds,
180+
pool=config.pool_timeout_seconds,
181+
),
182+
limits=httpx.Limits(
183+
max_connections=config.max_connections,
184+
max_keepalive_connections=config.max_keepalive_connections,
185+
),
186+
)
187+
self._concurrency_limit = ConcurrencyLimit(
188+
config.max_concurrent_requests,
178189
)
179190

180191
def __enter__(self) -> "ApiCall":
@@ -519,14 +530,15 @@ def _make_request_and_process_response(
519530
**kwargs: typing.Unpack[SessionFunctionKwargs[TParams, TBody]],
520531
) -> typing.Union[TEntityDict, str]:
521532
"""Make the async API request to `node` and process the response."""
522-
request_response = self.request_handler.make_request(
523-
method=method,
524-
url=url,
525-
as_json=as_json,
526-
entity_type=entity_type,
527-
client=self._client,
528-
**kwargs,
529-
)
533+
with self._concurrency_limit:
534+
request_response = self.request_handler.make_request(
535+
method=method,
536+
url=url,
537+
as_json=as_json,
538+
entity_type=entity_type,
539+
client=self._client,
540+
**kwargs,
541+
)
530542
self.node_manager.set_node_health(node, is_healthy=True)
531543
return (
532544
typing.cast(TEntityDict, request_response)

0 commit comments

Comments
 (0)