Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions backend/app/dependencies/rate_limit.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@
# Recommendations is an expensive DB scan + ML scoring pass; frontend caches
# results in localStorage for 5 min so legitimate users rarely exceed 1 req/min.
# Keeping this low prevents any single user from hammering the pipeline.
RECOMMENDATIONS_AUTH_LIMIT = 5
RECOMMENDATIONS_GUEST_LIMIT = 3
RECOMMENDATIONS_AUTH_LIMIT = 20
RECOMMENDATIONS_GUEST_LIMIT = 10

# ip -> deque of monotonic timestamps within the current window
_request_log: dict[str, deque] = defaultdict(deque)
Expand Down Expand Up @@ -101,10 +101,12 @@ async def recommendations_rate_limit(
"""
Rate limit for the recommendations endpoint — applies to ALL callers.

Guests: 3 req/min — low because they have no persistent state.
Authenticated: 5 req/min — the frontend caches results in localStorage
for 5 min, so legitimate users rarely exceed 1 req/min.
The lower limit prevents pipeline abuse even with auth.
Guests: 10 req/min — reasonable for unauthenticated browsing.
Authenticated: 20 req/min — covers normal multi-page browsing patterns
(Discover has staleTime=0 so every mount fires a request;
Matches caches for 5 min in localStorage so contributes
far less). 20 is well above legitimate use while still
blocking deliberate pipeline hammering.
"""
ip = _get_client_ip(request)
now = time.monotonic()
Expand All @@ -121,7 +123,7 @@ async def recommendations_rate_limit(
if len(log) >= limit:
raise HTTPException(
status_code=429,
detail=f"Too many requests. Recommendations are limited to {limit} per minute. Please wait before refreshing.",
detail=f"Too many requests. Please wait before refreshing.",
headers={"Retry-After": str(window)},
)

Expand Down
Loading
Loading