Skip to content

Commit 18eb055

Browse files
committed
perf: replace EXAPP_CACHE_LOCK with singleflight, add negative cache with bounded eviction
Signed-off-by: Oleksander Piskun <oleksandr2088@icloud.com>
1 parent 2e19466 commit 18eb055

1 file changed

Lines changed: 13 additions & 1 deletion

File tree

haproxy_agent.py

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
# SPDX-License-Identifier: AGPL-3.0-or-later
55

66
import asyncio
7+
import collections
78
import contextlib
89
import io
910
import ipaddress
@@ -240,7 +241,7 @@ def validate_expose_payload(self) -> Self:
240241

241242
EXAPP_CACHE: dict[str, ExApp] = {}
242243
_EXAPP_INFLIGHT: dict[str, asyncio.Future[ExApp | None]] = {}
243-
_EXAPP_NEGATIVE_CACHE: dict[str, float] = {} # exapp_id -> expiry monotonic timestamp
244+
_EXAPP_NEGATIVE_CACHE: collections.OrderedDict[str, float] = collections.OrderedDict()
244245
_NEGATIVE_CACHE_TTL = 15.0 # seconds to cache "ExApp not found" results
245246

246247
SESSION_CACHE_LOCK = asyncio.Lock()
@@ -594,6 +595,16 @@ async def _fetch_exapp_record(exapp_id: str) -> ExApp | None:
594595
return exapp_record
595596

596597

598+
def _negative_cache_evict_expired() -> None:
599+
"""Remove expired entries from the front of the ordered negative cache."""
600+
now = time.monotonic()
601+
while _EXAPP_NEGATIVE_CACHE:
602+
_, expiry = next(iter(_EXAPP_NEGATIVE_CACHE.items()))
603+
if now < expiry:
604+
break
605+
_EXAPP_NEGATIVE_CACHE.popitem(last=False)
606+
607+
597608
async def _get_or_fetch_exapp(exapp_id: str) -> ExApp | None:
598609
"""Get ExApp from cache, or fetch with request coalescing.
599610
@@ -632,6 +643,7 @@ async def _get_or_fetch_exapp(exapp_id: str) -> ExApp | None:
632643
LOGGER.info("Received new ExApp record: %s", exapp_record)
633644
EXAPP_CACHE[exapp_id] = exapp_record
634645
else:
646+
_negative_cache_evict_expired()
635647
_EXAPP_NEGATIVE_CACHE[exapp_id] = time.monotonic() + _NEGATIVE_CACHE_TTL
636648
fut.set_result(exapp_record)
637649
return exapp_record

0 commit comments

Comments
 (0)