🔧(backend) configure RedisCache in production settings

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.
This commit is contained in:
Anthony LC
2024-04-12 13:54:44 +02:00
committed by Anthony LC
parent 2f4dd4ee7a
commit 056bad08a5
2 changed files with 17 additions and 0 deletions

View File

@@ -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):
"""

View File

@@ -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",