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:
ksmithandClaude Sonnet 5 committed 2026-10-31 16:09:28 -06:00
1 parent b33fe905d2
commit abf4cef55b
6 files changed
+173 -4

No files matched your search

+4
View File
@@ -19,6 +19,7 @@ from apps.articles.models import (
get_system_tag,
)
from apps.articles.queries import with_user_state
from apps.core.cache_utils import invalidate_sidebar_unread_cache
from apps.feeds.models import Feed
FILTER_CHOICES = [
@@ -240,6 +241,7 @@ def mark_all_read(request):
for aid in new_article_ids
]
)
invalidate_sidebar_unread_cache(request.user.pk)
stream_url = reverse("reader:stream")
query = request.GET.urlencode()
@@ -254,6 +256,7 @@ def _load_article_and_mark_read(user, article_id):
state.is_read = True
state.read_at = timezone.now()
state.save(update_fields=["is_read", "read_at"])
invalidate_sidebar_unread_cache(user.pk)
article.is_read = state.is_read
article.is_starred, article.is_saved_for_later = _article_tag_flags(user, article)
@@ -285,6 +288,7 @@ def toggle_read(request, article_id):
state.is_read = not state.is_read
state.read_at = timezone.now() if state.is_read else None
state.save(update_fields=["is_read", "read_at"])
invalidate_sidebar_unread_cache(request.user.pk)
article.is_read = state.is_read
article.is_starred, article.is_saved_for_later = _article_tag_flags(request.user, article)