Skip to content

fix: add LRU eviction to session/replay caches to reduce RAM usage#40

Closed
Clav3rbot wants to merge 1 commit intoadn8naiagent:devfrom
Clav3rbot:fix/memory-management
Closed

fix: add LRU eviction to session/replay caches to reduce RAM usage#40
Clav3rbot wants to merge 1 commit intoadn8naiagent:devfrom
Clav3rbot:fix/memory-management

Conversation

@Clav3rbot
Copy link
Copy Markdown
Contributor

What

Adds LRU eviction policies to the two largest in-memory caches and a manual cache-clear admin endpoint.

Why

The backend consumes 1-2 GB of RAM that is never freed, even after all clients disconnect. The root cause is two unbounded caches:

  • _session_cache in services/f1_data.py: stores full fastf1.core.Session objects (200-800 MB each) indefinitely
  • _replay_cache in routers/replay.py: stores all replay frames for every viewed session indefinitely

As users browse different sessions, memory grows without bound and is never reclaimed.

How

  • LRU eviction for session cache: replaced plain dict with OrderedDict-based LRU. Default max 2 sessions (configurable via SESSION_CACHE_MAX env var). Oldest sessions are evicted + gc.collect() on insert.
  • LRU eviction for replay cache: same pattern, default max 3 entries (configurable via REPLAY_CACHE_MAX env var).
  • clear_session_cache() / clear_replay_cache(): helper functions that clear all entries and trigger garbage collection.
  • POST /api/admin/cache/clear: new endpoint to manually release all caches and reclaim memory on demand.

Expected Impact

RAM usage capped at ~1-1.6 GB max (2 sessions) instead of growing indefinitely. Memory is proactively freed when new sessions are loaded.

…endpoint

- Replace unbounded _session_cache dict with OrderedDict LRU (max 2, configurable via SESSION_CACHE_MAX env var). Each fastf1 Session holds 200-800MB; without eviction memory grows indefinitely.
- Replace unbounded _replay_cache dict with OrderedDict LRU (max 3, configurable via REPLAY_CACHE_MAX env var).
- Add clear_session_cache() and clear_replay_cache() helpers with gc.collect().
- Add POST /api/admin/cache/clear endpoint to manually release all in-memory caches.
@adn8naiagent
Copy link
Copy Markdown
Owner

Apologies @Clav3rbot, I had picked up this issue and been fixing it along with a few of the other items you've raised as PRs. Have fixed to evict cache after session no longer actively used.
Appreciate your contributions to to project

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants