From 056bad08a570274cbdd924563977141256577918 Mon Sep 17 00:00:00 2001 From: Anthony LC Date: Fri, 12 Apr 2024 13:54:44 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7(backend)=20configure=20RedisCache?= =?UTF-8?q?=20in=20production=20settings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In development, sessions are saved in local memory. It's working well, however it doesn't adapt to a kubernetized setup. Several pods need to access the current sessions, which need to be stored in a single source of truth. With a local memory cache, pods cannot read session saved in other pods. We end up returning 401 errors, because we cannot authenticate the user. I preferred setting up a proper cache than storing sessions in database, because in the long run it would be a performance bottleneck. Cache will decrease data access latency when reading current sessions. I added a Redis cache backend to the production settings. Sessions would be persisted to Redis. In K8s, a Redis operator will make sure the cached data are not lost. Two new dependencies were added, redis and django-redis. I followed the installation guide of django-redis dependency. These setting were tested deploying the app to a local K8s cluster. --- src/backend/impress/settings.py | 15 +++++++++++++++ src/backend/pyproject.toml | 2 ++ 2 files changed, 17 insertions(+) diff --git a/src/backend/impress/settings.py b/src/backend/impress/settings.py index 6696952a..fb72d34b 100755 --- a/src/backend/impress/settings.py +++ b/src/backend/impress/settings.py @@ -277,6 +277,7 @@ class Base(Configuration): # Session SESSION_ENGINE = "django.contrib.sessions.backends.cache" + SESSION_CACHE_ALIAS = "default" SESSION_COOKIE_AGE = 60 * 60 * 12 # OIDC - Authorization Code Flow @@ -531,6 +532,20 @@ class Production(Base): AWS_STORAGE_BUCKET_NAME = values.Value("tf-default-impress-media-storage") AWS_S3_REGION_NAME = values.Value() + CACHES = { + "default": { + "BACKEND": "django_redis.cache.RedisCache", + "LOCATION": values.Value( + "redis://redis:6379/1", + environ_name="REDIS_URL", + environ_prefix=None, + ), + "OPTIONS": { + "CLIENT_CLASS": "django_redis.client.DefaultClient", + }, + }, + } + class Feature(Production): """ diff --git a/src/backend/pyproject.toml b/src/backend/pyproject.toml index 502cc821..07aa6c23 100644 --- a/src/backend/pyproject.toml +++ b/src/backend/pyproject.toml @@ -32,6 +32,8 @@ dependencies = [ "django-cors-headers==4.3.1", "django-countries==7.5.1", "django-parler==2.3", + "redis==5.0.3", + "django-redis==5.4.0", "django-storages==1.14.2", "django-timezone-field>=5.1", "django==5.0.3",