feat: Implement LLM call caching
Closes #241
📝 Description
This PR fixes the unnecessary LLM API calls made by the user either in the Discord or GitHub channels by implementing a multi-layer caching and optimization system for message classification.
🔧 Changes Made
cache_helpers.py
- Simplified hashing: Replaced with single XXHash128, reducing CPU overhead and reducing collision
- Added
MAX_MESSAGE_LENGTH(10KB): Truncates oversized messages before processing to prevent DoS attacks and excessive memory usage patches security issues - Bounded in-flight tracking: Replaced unbounded
_inflightdict withTTLCache(maxsize=1000, ttl=120)to prevent memory leaks from orphaned requests - Fixed orphaned future bug: Added
asyncio.CancelledErrorhandling to prevent request hangs when tasks are cancelled
classification_router.py
- Added LLM concurrency limiter: Implemented
asyncio.Semaphore(10)to limit concurrent LLM API calls, preventing rate limit errors and cost explosions during traffic spikes - Added message length validation: Early return for messages exceeding
MAX_MESSAGE_LENGTHwith fallback classification
Impact
Optimization Summary
| Optimization | Impact |
|---|---|
| Pattern matching fast-path | 30-50% cached messages skip LLM entirely |
| Result caching | Repeated questions served instantly |
| In-flight deduplication | Concurrent identical requests share one LLM call |
| Concurrency limiter | Max 10 simultaneous LLM calls |
✅ Checklist
- [x] I have read the contributing guidelines.
- [x] I have added tests that prove my fix is effective or that my feature works.
- [x] I have added necessary documentation (if applicable).
- [x] Any dependent changes have been merged and published in downstream modules.
Summary by CodeRabbit
- New Features
- Added an asynchronous caching layer for message classification to speed repeated or similar requests.
- Added pattern-based fast-path detection to return immediate results for common messages.
- Deduplicated concurrent identical requests so only one backend call is performed.
- Implemented concurrency limits and message-size safeguards to protect system stability.
- Exposed runtime metrics for total requests, cache hits/misses, and skipped LLM calls.
✏️ Tip: You can customize this high-level summary in your review settings.
Adds a new asynchronous LLM caching layer (TTL LRU + in‑flight dedupe), message normalization and regex fast‑path classification, and integrates these into ClassificationRouter with concurrency limiting, message length guards, metrics, and fallback triage behavior. 🎯 4 (Complex) | ⏱️ ~60 minutes 🐰 Hopping through prompts, I tidy and sort, Keys clack and futures wait in a cozy fort. ✏️ Tip: You can configure your own custom pre-merge checks in the settings.📝 Walkthrough
Walkthrough
Changes
Cohort / File(s)
Summary
Caching Infrastructure
backend/app/classification/cache_helpers.pyNew module: TTL LRU cache and in‑flight dedupe, stable key generation (XXHash or blake2b fallback), message normalization, regex pattern fast‑path classification, cache get/set helpers, async
cached_llm_call orchestration, and metrics counters.
Classification Router Integration
backend/app/classification/classification_router.pyIntegrates cache_helpers: adds a global semaphore for concurrency control, message length guard, normalization, fast‑path skip, normalized cache lookup/store, metrics increments, guarded LLM invocation, JSON parse of LLM payload, and fallback triage on error.
Sequence Diagram(s)
sequenceDiagram
participant Client as Message Request
participant Router as ClassificationRouter
participant Helper as cache_helpers
participant Cache as TTL Cache
participant Inflight as In‑flight Registry
participant LLM as LLM Service
Client->>Router: should_process_message(message, context)
Router->>Helper: normalize_message(message)
Helper-->>Router: normalized
Router->>Helper: is_simple_message(normalized)
Helper-->>Router: fast‑path result or None
alt fast‑path
Router-->>Client: return classification
else
Router->>Helper: key_for_normalized(normalized,...)
Router->>Helper: get_cached_by_normalized(...)
Helper->>Cache: lookup
Cache-->>Helper: cached payload or miss
Helper-->>Router: payload or None
alt cache hit
Router-->>Client: return cached classification
else cache miss
Router->>Inflight: check/register future for key
alt another inflight exists
Inflight-->>Router: await shared future -> result
else owner:
Router->>LLM: ainvoke(triage prompt) (guarded by semaphore)
LLM-->>Router: response
Router->>Helper: set_cached_by_normalized(..., payload)
Router->>Inflight: resolve future + cleanup
end
Router-->>Client: return classification
end
end
Estimated code review effort
Possibly related PRs
Suggested reviewers
Poem
Greetings answered quick, repeated asks spared,
One cached nibble saved many a call dared.
A rabbit's small hop and tokens are spared.🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
Check name
Status
Explanation
Resolution
Docstring Coverage
⚠️ Warning
Docstring coverage is 58.33% which is insufficient. The required threshold is 80.00%.
Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name
Status
Explanation
Description Check
✅ Passed
Check skipped - CodeRabbit’s high-level summary is enabled.
Title check
✅ Passed
The PR title 'feat: Implement LLM call caching' directly and accurately describes the primary change: adding caching functionality for LLM calls.
Linked Issues check
✅ Passed
All coding requirements from issue
#241 are implemented: pattern matching for simple messages, LRU cache with TTL, message normalization, in-flight deduplication, concurrency limiting, and metrics tracking.
Out of Scope Changes check
✅ Passed
All changes are scoped to the caching and optimization objectives from issue
#241. No unrelated modifications detected beyond the stated enhancement goals.✨ Finishing touches
🧹 Recent nitpick comments
backend/app/classification/cache_helpers.py (2)
14-19: Refine exception type toImportError.The xxhash import is correctly moved inside the try block, but catching broad
Exceptionis overly permissive. UseImportErrorfor precision and to satisfy the static analysis hint (BLE001).♻️ Proposed fix
try: import xxhash _HAS_XXHASH = True -except Exception: +except ImportError: xxhash = None _HAS_XXHASH = False
101-104: Consider logging when JSON serialization fails.The fallback to
str(params)is reasonable but could produce inconsistent cache keys ifparamscontains objects with unstable__str__representations. Adding a debug log would help identify problematic inputs.♻️ Proposed fix
try: params_blob = json.dumps(params or {}, sort_keys=True, separators=(",", ":"), default=str).encode("utf-8") - except Exception: + except (TypeError, ValueError) as e: + logger.debug(f"JSON serialization failed for params, using str fallback: {e}") params_blob = str(params).encode("utf-8")
📜 Recent review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 9d1db32f30c6362be866cdfcf44d367c8df69156 and c66b9fb37ab833bc7ca10867d16778d16ea62a94.
📒 Files selected for processing (1)
backend/app/classification/cache_helpers.py
🧰 Additional context used
🪛 Ruff (0.14.11)
backend/app/classification/cache_helpers.py
17-17: Do not catch blind exception: Exception
(BLE001)
103-103: Do not catch blind exception: Exception
(BLE001)
188-188: Consider moving this statement to an else block
(TRY300)
🔇 Additional comments (5)
backend/app/classification/cache_helpers.py (5)
21-58: LGTM!The configuration constants are sensible and the regex patterns are well-structured for fast-path classification. The patterns cover a good range of common message types including Discord-specific patterns.
82-87: LGTM!Good use of bounded TTLCache for both the main cache and in-flight deduplication. The TTL on
_inflightprevents memory leaks from orphaned requests.
141-224: Well-implemented async caching with proper task management.The in-flight deduplication logic is solid:
- Atomic future installation via
setdefaultcorrectly handles race conditions.- The owner task reference is stored and tracked.
- Done callback propagates exceptions to waiting callers.
- Cancellation is properly handled by cancelling the owner task and awaiting it.
The
elapsedvariable is now used for logging, and the task reference is properly managed.
226-231: LGTM!The
normalize_messagefunction correctly handles truncation for DoS prevention, trims whitespace, lowercases, and collapses multiple whitespace characters into single spaces.
238-247: LGTM!Simple and effective cache accessor functions with proper KeyError handling.
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
Comment @coderabbitai help to get the list of available commands and usage tips.
@smokeyScraper @chandansgowda Can you review this I think I have implemented it the best I could any insights from you guys ?
Hey, @smokeyScraper if you get the time can you please review this ?