Skip to content

Added django-redis as default cache #1371

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 21 commits into
base: main
Choose a base branch
from

Conversation

Rajgupta36
Copy link
Collaborator

@Rajgupta36 Rajgupta36 commented Apr 14, 2025

Resolves #1352

Task

  • Added django-redis as the default caching system for the project.

Additional Info :-

  • I used 25 MB of RAM for the local and staging environments, which can store around 300–500 entries of project page size.
  • In production, we provide 100 MB of memory, which can store around 1200–1500 entries.

@Rajgupta36 Rajgupta36 requested a review from arkid15r as a code owner April 14, 2025 12:08
Copy link
Contributor

coderabbitai bot commented Apr 14, 2025

Summary by CodeRabbit

  • New Features
    • Integrated Redis as the cache backend for improved performance.
    • Added Redis services to local, staging, and production environments with secure configuration and health checks.
  • Chores
    • Updated environment variable examples and deployment workflows to support Redis configuration.
    • Included Redis client tools in the backend runtime environment.
  • Tests
    • Improved test reliability by mocking Redis cache in relevant test cases.
  • Documentation
    • Added "requirepass" to the custom dictionary for spelling consistency.

Summary by CodeRabbit

  • New Features
    • Enabled Redis caching for enhanced backend performance.
    • Integrated new Redis services across local, staging, and production environments.
  • Chores
    • Updated deployment workflows and environment configurations to securely inject Redis connection details.
    • Added a dependency to support the new caching mechanism.
  • Tests
    • Improved test reliability by introducing an automated Redis cache mock setup.

Walkthrough

This pull request introduces Redis support for the backend application. It adds new Redis-related environment variables in the CI/CD workflows and example environment files, updates the Django cache configuration to use Redis with appropriate client settings, and adds the django-redis dependency. Redis services with memory limits, health checks, volume mounts, and network configurations are added to local, staging, and production Docker Compose files. Backend services are updated to depend on the Redis cache services. Additionally, test code is modified to mock Redis cache automatically.

Changes

File(s) Change Summary
.github/workflows/run-ci-cd.yaml Added Redis environment variables (DJANGO_REDIS_HOST, DJANGO_REDIS_PASSWORD, DJANGO_REDIS_PORT) injection in staging and production deployment jobs.
backend/.env.example Added Redis environment variables (DJANGO_REDIS_HOST, DJANGO_REDIS_PASSWORD, DJANGO_REDIS_PORT) initialized to None.
backend/pyproject.toml Added django-redis dependency version ^5.4.0.
backend/settings/base.py Updated Django cache backend to use Redis (django_redis.cache.RedisCache), configured via environment variables for host, password, and port; added Redis client options and cache timeout.
docker/docker-compose-local.yaml Added cache Redis service with password, memory limit, eviction policy, health check, volume, and network; updated backend service to depend on cache service and set Redis environment variables.
docker/docker-compose-staging.yaml Added staging-nest-cache Redis service with password, memory limit, eviction policy, health check, volume, and network; updated backend service to depend on staging-nest-cache and include Redis network; adjusted frontend.
docker/docker-compose-production.yaml Added production-nest-cache Redis service with password, memory limit, eviction policy, health check, volume, and network; updated backend service to depend on production-nest-cache and include Redis network; adjusted frontend.
backend/tests/apps/core/api/algolia_test.py Removed manual cache clearing fixture; added automatic mock Redis cache fixture; simplified parameterized test comments.
cspell/custom-dict.txt Added the word "requirepass" to the custom dictionary.
backend/docker/Dockerfile.local Added installation of Redis client tools (redis package) to the runtime environment.

Assessment against linked issues

Objective Addressed Explanation
Migrate Django to use Redis cache (#1352)
Configure Docker Redis services with environment-specific memory limits (#1352)

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ebefc2c and 9ab9f10.

⛔ Files ignored due to path filters (1)
  • backend/poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • cspell/custom-dict.txt (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cspell/custom-dict.txt
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Run frontend e2e tests
  • GitHub Check: Run frontend unit tests
  • GitHub Check: Run backend tests
  • GitHub Check: CodeQL (python)
  • GitHub Check: CodeQL (javascript-typescript)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
backend/settings/base.py (1)

134-134: Consider adding a fallback cache mechanism.

For resilience, consider adding a fallback local memory cache when Redis is unavailable. This is particularly important for critical application functionality.

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": values.SecretValue(environ_name="DJANGO_REDIS_URL"),
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        },
    },
+   "fallback": {
+       "BACKEND": "django.core.cache.backends.locmem.LocMemCache",
+       "LOCATION": "fallback",
+       "TIMEOUT": 300,
+   }
}

You can then implement a custom cache class that falls back to the local memory cache when Redis is unavailable.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 09de2e9 and 10658fa.

⛔ Files ignored due to path filters (1)
  • backend/poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • .github/workflows/run-ci-cd.yaml (2 hunks)
  • backend/.env.example (1 hunks)
  • backend/pyproject.toml (1 hunks)
  • backend/settings/base.py (1 hunks)
  • docker/docker-compose-local.yaml (2 hunks)
  • docker/docker-compose-production.yaml (2 hunks)
  • docker/docker-compose-staging.yaml (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run frontend unit tests
  • GitHub Check: Run frontend e2e tests
  • GitHub Check: Run backend tests
🔇 Additional comments (10)
backend/pyproject.toml (1)

30-30: Good dependency addition.

The addition of django-redis is appropriate for implementing Redis as the default caching system as per the PR objectives. Version constraint ^5.4.0 follows good semantic versioning practices.

.github/workflows/run-ci-cd.yaml (2)

326-326: Properly added Redis URL to staging environment.

The Redis URL is correctly added to the environment variables for the staging deployment, maintaining security by using secrets.


494-494: Properly added Redis URL to production environment.

The Redis URL is correctly added to the environment variables for the production deployment, maintaining security by using secrets.

docker/docker-compose-local.yaml (3)

15-16: Dependency Addition for Backend Service
The inclusion of the redis dependency in the backend service (depends_on block) ensures that the backend will wait until Redis reports as healthy before starting. This aligns well with the PR objective of integrating Redis as the default cache.


91-105: Addition of the Redis Service for Local Environment
The newly added redis service is configured with the appropriate image (redis:7.2-alpine), memory limit (25mb), eviction policy (allkeys-lru), and health check settings. This ensures proper local caching behavior based on the resource allocation described in the PR objectives.


111-115: Volume Declaration for Redis Persistence
The declaration of the redis-data volume within the volumes section is essential for data persistence. It complements the Redis service configuration by ensuring that cache data survives container restarts.

docker/docker-compose-staging.yaml (2)

9-10: Updated Dependency for Staging Backend
The staging backend service now depends on staging-nest-redis (with the condition set to service_healthy). This change correctly enforces startup order so that the backend service only initiates after the Redis service is operational, matching the PR goals for the staging environment.


40-55: Addition of the Staging Redis Service
The new staging-nest-redis service is appropriately configured with the image, command settings (using a 25 MB memory limit), volume mapping, port exposure, and health check parameters. These settings meet the staging environment’s resource guidelines and enhance the caching strategy.

docker/docker-compose-production.yaml (2)

9-10: Updated Dependency for Production Backend
The dependency update in the production-nest-backend service now includes production-nest-redis, ensuring that the backend only starts once the Redis service is confirmed healthy. This is consistent with the production cache integration strategy.


40-55: Addition of the Production Redis Service
The production Redis service is properly spun up with a higher memory allocation (100mb) to support increased load, as specified in the PR objectives. The service’s configuration—including image selection, command options, volume mapping, port exposure, and health check settings—is well aligned with the production requirements.

@@ -12,6 +12,7 @@ DJANGO_DB_PORT=None
DJANGO_DB_USER=None
DJANGO_OPEN_AI_SECRET_KEY=None
DJANGO_PUBLIC_IP_ADDRESS="127.0.0.1"
DJANGO_REDIS_URL=redis://nest-redis:6379/1
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Environment variable naming needs consistency check.

While the Redis URL format is correct, there appears to be a naming inconsistency. This environment variable is named DJANGO_REDIS_URL but in base.py it's referenced as REDIS_URL (without the DJANGO_ prefix).


🏁 Script executed:

#!/bin/bash
# Check for environment variable name consistency between settings and example file

# Look for REDIS_URL reference in settings files
echo "Checking how Redis URL is referenced in settings files:"
rg -A 1 -B 1 "REDIS_URL" backend/settings/

Length of output: 389


Inconsistent Redis environment variable naming detected

  • The .env.example file defines the variable as DJANGO_REDIS_URL (line 15), but in backend/settings/base.py it is referenced as REDIS_URL via values.SecretValue(environ_name="REDIS_URL").
  • Please update one of these references to ensure consistency—likely by renaming DJANGO_REDIS_URL to REDIS_URL in the .env.example file.

Comment on lines 127 to 132
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": values.SecretValue(environ_name="REDIS_URL"),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
}
Copy link
Contributor

@coderabbitai coderabbitai bot Apr 14, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Redis cache configuration needs improvement.

The Redis cache configuration is functional but has some issues to address:

  1. There's a naming inconsistency: In .env.example the variable is named DJANGO_REDIS_URL but here it's referenced as REDIS_URL.
  2. Missing cache timeout and other recommended settings.

Apply the following changes to fix the naming inconsistency and add recommended settings:

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
-       "LOCATION": values.SecretValue(environ_name="REDIS_URL"),
+       "LOCATION": values.SecretValue(environ_name="DJANGO_REDIS_URL"),
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
+           "IGNORE_EXCEPTIONS": True,  # Prevents cache-related exceptions from breaking the site
        },
+       "TIMEOUT": 300,  # 5 minutes default timeout
    }
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": values.SecretValue(environ_name="REDIS_URL"),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
}
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": values.SecretValue(environ_name="DJANGO_REDIS_URL"),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
"IGNORE_EXCEPTIONS": True, # Prevents cache-related exceptions from breaking the site
},
"TIMEOUT": 300, # 5 minutes default timeout
}
}

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Rajgupta36 could you take a look at these extra configuration params -- some of them may be userful.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Collaborator

@arkid15r arkid15r left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please check the following when you get a chance:

Comment on lines 127 to 132
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": values.SecretValue(environ_name="REDIS_URL"),
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Rajgupta36 could you take a look at these extra configuration params -- some of them may be userful.

@@ -490,6 +491,7 @@ jobs:
echo "DJANGO_DB_USER=${{ secrets.DJANGO_DB_USER }}" >> .env.backend
echo "DJANGO_OPEN_AI_SECRET_KEY=${{ secrets.DJANGO_OPEN_AI_SECRET_KEY }}" >> .env.backend
echo "DJANGO_RELEASE_VERSION=${{ github.event.release.tag_name }}" >> .env.backend
echo "DJANGO_REDIS_URL=${{ secrets.DJANGO_REDIS_URL }}" >> .env.backend
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please re-order it.

@@ -86,12 +88,30 @@ services:
- frontend-next:/home/owasp/.next
- frontend-node-modules:/home/owasp/node_modules

redis:
container_name: nest-redis
image: redis:7.2-alpine
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you pin this version to the patch value, e.g. redis:7.2.7-alpine3.21 -- use 7.2.? instead of just 7.2

volumes:
backend-venv:
db-data:
redis-data:
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make it consistent w/ other volume names (no specific technology mentioned)

Suggested change
redis-data:
cache-data:

@Rajgupta36 Rajgupta36 requested a review from arkid15r April 21, 2025 22:33
Copy link
Collaborator

@arkid15r arkid15r left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reworked the configuration a bit, please take a look.
Could you also implement an authenticated access to redis?

Thank you!

@Rajgupta36 Rajgupta36 requested a review from arkid15r April 22, 2025 10:34
@github-actions github-actions bot added the docker Pull requests that update Docker code label Apr 23, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
backend/docker/Dockerfile.local (1)

22-24: Optimize APK install to avoid index caching and clarify Redis package selection

Using apk update && apk add caches the index and increases image size. You can simplify this into a single command with --no-cache to skip storing the index. Additionally, if the container only needs the Redis CLI (and not the full server), consider installing redis-cli instead of the redis package.

Proposed diff:

-RUN apk update && \
-    apk add postgresql-client redis && \
+RUN apk add --no-cache postgresql-client redis && \

Did you intend to install the full Redis server, or only the CLI tools?

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ae0b510 and ebefc2c.

⛔ Files ignored due to path filters (1)
  • backend/poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • .github/workflows/run-ci-cd.yaml (2 hunks)
  • backend/.env.example (1 hunks)
  • backend/docker/Dockerfile.local (1 hunks)
  • backend/settings/base.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • backend/.env.example
  • .github/workflows/run-ci-cd.yaml
  • backend/settings/base.py
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Run frontend e2e tests

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backend backend-tests ci docker Pull requests that update Docker code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Implement redis cache support
2 participants