From 8ad6a0daa961302fc59b0aec72a76f2f69449e96 Mon Sep 17 00:00:00 2001 From: Leo Franchi Date: Fri, 6 Sep 2013 14:50:25 -0400 Subject: [PATCH] Cache realm alert_words to avoid database hits when rendering We found that since bugdown processes are threaded, the cost of doing a db query in a markdown processor is quite high---each thread must start up a new db connection including a SSL handshake etc. We should strive to keep our rendering pipeline free of mandatory DB queries. (imported from commit 555066bd03da6c681b74ce6137acc264eb41c55d) --- zerver/lib/alert_words.py | 3 +++ zerver/lib/cache.py | 8 ++++++++ 2 files changed, 11 insertions(+) diff --git a/zerver/lib/alert_words.py b/zerver/lib/alert_words.py index f7a080d052..35a0081cb8 100644 --- a/zerver/lib/alert_words.py +++ b/zerver/lib/alert_words.py @@ -2,10 +2,13 @@ import re import zerver.models +from zerver.lib.cache import cache_with_key, realm_alert_words_cache_key + import itertools import logging import ujson +@cache_with_key(realm_alert_words_cache_key, timeout=3600*24) def alert_words_in_realm(realm): users = zerver.models.UserProfile.objects.filter(realm=realm, is_active=True) all_user_words = dict((user, user_alert_words(user)) for user in users) diff --git a/zerver/lib/cache.py b/zerver/lib/cache.py index 68376ac5da..77aecfbc67 100644 --- a/zerver/lib/cache.py +++ b/zerver/lib/cache.py @@ -242,6 +242,11 @@ def update_user_profile_cache(sender, **kwargs): items_for_memcached[user_profile_by_id_cache_key(user_profile.id)] = (user_profile,) cache_set_many(items_for_memcached) + # Invalidate realm-wide alert words cache if any user in the realm has changed + # alert words + if kwargs['update_fields'] is None or "alert_words" in kwargs['update_fields']: + djcache.delete(KEY_PREFIX + realm_alert_words_cache_key(user_profile.realm)) + def status_dict_cache_key(user_profile): return "status_dict:%d" % (user_profile.realm_id,) @@ -251,3 +256,6 @@ def update_user_presence_cache(sender, **kwargs): # If the status of the user changed, flush the user's realm's # entry in the UserPresence cache to avoid giving out stale state djcache.delete(KEY_PREFIX + status_dict_cache_key(user_profile)) + +def realm_alert_words_cache_key(realm): + return "realm_alert_words:%s" % (realm.domain,)