Private
Public Access
Cache sidebar unread counts for a short TTL (C3)
apps.core.context_processors.sidebar runs on every authenticated page
render and called unread_counts_by_feed, a join/group-by over the
user's whole article corpus, every single time — cost grew with the
archive's size regardless of which page was being viewed.
unread_counts_by_feed now caches its {feed_id: count} result per user
for 30 seconds (apps.core.cache_utils). The reader views that change
the current user's own read state (toggle_read, mark_all_read, viewing
an article) invalidate it immediately so the sidebar never visibly lags
behind the action that just caused it; other paths (rule-driven state
changes during background ingestion) aren't explicitly invalidated and
simply self-heal within the TTL, which is an acceptable tradeoff
already made elsewhere in this app (the stream's own "new articles"
banner polls on the same 30s cadence).
Also adds a global cache.clear() autouse fixture (conftest.py) — the
test CACHES backend (LocMemCache) lives in process memory and survives
Django's per-test DB rollback, so a cached count keyed by a user's pk
could otherwise leak into an unrelated later test reusing that pk.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b33fe905d2
commit
abf4cef55b
6 files changed
+173
-4
No files matched your search
@@ -0,0 +1,22 @@
|
||||
from django.core.cache import cache
|
||||
|
||||
# Short enough that a missed invalidation point self-heals within one
|
||||
# page load's worth of staleness; long enough to actually absorb repeat
|
||||
# authenticated-page renders (apps.core.context_processors.sidebar runs
|
||||
# on every one) without recomputing unread_counts_by_feed's join/group-by
|
||||
# over the user's whole article corpus each time (C3).
|
||||
SIDEBAR_UNREAD_CACHE_TTL_SECONDS = 30
|
||||
|
||||
|
||||
def sidebar_unread_cache_key(user_id: int) -> str:
|
||||
return f"sidebar-unread:{user_id}"
|
||||
|
||||
|
||||
def invalidate_sidebar_unread_cache(user_id: int) -> None:
|
||||
"""Call this wherever a request changes the current user's own
|
||||
read/unread state (toggle_read, mark_all_read, viewing an article) so
|
||||
the sidebar reflects it on the very next render instead of waiting
|
||||
out the TTL above. Rule-driven state changes during background feed
|
||||
ingestion aren't invalidated this way — those self-heal within the
|
||||
TTL, same as a missed call site here would."""
|
||||
cache.delete(sidebar_unread_cache_key(user_id))
|
||||
Reference in new issue
Block a user