Skip to content

increased client cache timer from a day to a year and changes static file generation into S3ManifestStaticStorage for cache busting strategy#1172

Open
YuDavidCao wants to merge 4 commits intodevfrom
aws/increase-client-cache-timer
Open

increased client cache timer from a day to a year and changes static file generation into S3ManifestStaticStorage for cache busting strategy#1172
YuDavidCao wants to merge 4 commits intodevfrom
aws/increase-client-cache-timer

Conversation

@YuDavidCao
Copy link
Collaborator

@YuDavidCao YuDavidCao commented Oct 19, 2025

GitHub Issues addressed

  • This PR closes

What I did

  • Changed the original AWS_S3_OBJECT_PARAMETERS timer from a day to a year
  • To prevent newly generated static files not being fetched due to client caching, changed the original storages.backends.s3.S3Storage into storages.backends.s3.S3ManifestStaticStorage to generate a unique file hash when collecting static

Originally, if the time between two requests are longer than a day, it will refetch the static files again from S3 which is not very optimal. This change should change this refetch interval to a year.

In order to make sure that updated static files are being refetched after a new deployment, the S3ManifestStaticStorage will create a file hash in the file name. For example, base.css might be hashed into base.a1b2c3d4.css afterward. This should make sure that the frontend browser to refetch the static file if changed.

Online resources for documentation:

https://django-storages.readthedocs.io/en/1.11.1/backends/amazon-S3.html
https://docs.djangoproject.com/en/3.1/ref/contrib/staticfiles/#manifeststaticfilesstorage

Screenshots

  • Before
  • After

Testing

  • A brief explanation of tests done/written or how reviewers can test your work

Questions/Discussions/Notes

Summary by CodeRabbit

  • New Features

    • Static assets are now served from a dedicated S3 static URL/domain.
  • Performance Improvements

    • Static assets use long-term caching (365 days) to speed repeat visits and employ manifest-backed handling for reliable cache busting.
    • Media files use shorter caching (24 hours) so updates appear promptly.

…file generation into S3ManifestStaticStorage for cache busting strategy
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 19, 2025

Walkthrough

Reworked S3 storage settings: removed the old global AWS_S3_OBJECT_PARAMETERS, added STATIC_URL, set STORAGES["default"]["OPTIONS"] to use location="media" with 1‑day CacheControl, and switched STORAGES["staticfiles"] to manifest-backed storage with location="static" and 1‑year CacheControl.

Changes

Cohort / File(s) Summary
S3 settings & storage backends
tcf_core/settings/base.py
Removed global AWS_S3_OBJECT_PARAMETERS; added STATIC_URL; set STORAGES["default"]["OPTIONS"] to {"location": "media", "object_parameters": {"CacheControl": "max-age=86400"}}; changed STORAGES["staticfiles"]["BACKEND"] to storages.backends.s3.S3ManifestStaticStorage and added OPTIONS {"location": "static", "object_parameters": {"CacheControl": "max-age=31536000"}}.

Sequence Diagram(s)

sequenceDiagram
  participant Django as Django app
  participant S3Static as S3 (static, manifest)
  participant S3Media as S3 (media)

  Note over Django,S3Static: collectstatic -> manifest generation + upload
  Django->>S3Static: Upload static files (CacheControl: max-age=31536000)
  S3Static-->>Django: Serve STATIC_URL (https://<S3_DOMAIN>/static/)

  Note over Django,S3Media: user media uploads
  Django->>S3Media: Upload media files (CacheControl: max-age=86400)
  S3Media-->>Django: Serve media via default storage backend

  rect rgba(0,128,0,0.06)
    Note right of S3Static: Manifest-backed filenames enable long caching
  end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Check object_parameters structure and exact header names (CacheControl).
  • Verify STATIC_URL composition with AWS_S3_CUSTOM_DOMAIN / AWS_LOCATION.
  • Confirm storages.backends.s3.S3ManifestStaticStorage works with current collectstatic/manifest workflow.

Possibly related PRs

Suggested reviewers

  • Jay-Lalwani
  • ldkohler

Poem

A rabbit tugs the manifest thread, 🐇
Static snug for a year ahead,
Media bounces, one day to roam,
Buckets hum and point to home,
Deploy hops on — the code's well-bred.

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description Check ⚠️ Warning The PR description has the "What I did" section well-filled with comprehensive explanation of the changes, rationale, and documentation links. However, four of the five template sections are either empty or contain only placeholder text: the "GitHub Issues addressed" section is blank, "Screenshots" shows only placeholder text without actual content, "Testing" is not filled with actual testing details, and "Questions/Discussions/Notes" is empty. This leaves only 20% of the template sections properly completed, which falls short of being "mostly complete." The PR description should be completed according to the template. Please fill in the "GitHub Issues addressed" section (specifying which issue this closes or indicating if none), provide details about how the changes were tested or how reviewers can verify the changes, and complete the remaining template sections. While the "What I did" content is good, the overall description remains largely incomplete.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The PR title accurately describes the two main changes made in the changeset: increasing the client cache timer from one day to one year, and switching to S3ManifestStaticStorage for cache busting through filename hashing. The title is specific and clearly conveys the primary objectives without vague terminology. While somewhat lengthy at 140 characters, it remains appropriately detailed for a multi-part configuration change, and a reviewer can immediately understand the core purpose of the changes.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch aws/increase-client-cache-timer

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0b4c438 and b98ad46.

📒 Files selected for processing (1)
  • tcf_core/settings/base.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tcf_core/settings/base.py

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@YuDavidCao YuDavidCao marked this pull request as ready for review October 19, 2025 20:06
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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3c6b496 and 3b46944.

📒 Files selected for processing (1)
  • tcf_core/settings/base.py (2 hunks)
🔇 Additional comments (1)
tcf_core/settings/base.py (1)

93-93: Code change is safe—template compatibility and deployment process already verified.

Verification confirms all requirements for S3ManifestStaticStorage are met:

  • Templates use {% static %} tags correctly: All 68 templates properly load the static template tag and reference static files using {% static 'path/to/file' %} syntax (e.g., CSS stylesheets, images, JavaScript).
  • No hardcoded static paths: No broken references to /static/ or relative paths found in templates.
  • collectstatic in deployment pipeline: Deployment scripts already execute python manage.py collectstatic --noinput.

The backend upgrade from S3Storage to S3ManifestStaticStorage is properly configured and compatible with existing template structure.

AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com"
AWS_DEFAULT_ACL = None
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"}
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=31536000"} # 1 year cache
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Critical: Global cache control affects media files, not just static assets.

AWS_S3_OBJECT_PARAMETERS is a global django-storages setting that applies to all S3 storage backends, including the "default" storage used for media/user-uploaded files (line 89). Setting a 1-year cache on user-uploaded content is problematic—users won't see updated media files for up to a year.

Configure cache control per-backend instead:

-AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=31536000"}  # 1 year cache
+# Remove global AWS_S3_OBJECT_PARAMETERS - configure per backend instead
 STORAGES = {
     "default": {
         "BACKEND": "storages.backends.s3.S3Storage",
-        "OPTIONS": {},
+        "OPTIONS": {
+            "object_parameters": {"CacheControl": "max-age=86400"},  # 1 day for media
+        },
     },
     "staticfiles": {
         "BACKEND": "storages.backends.s3.S3ManifestStaticStorage",
+        "OPTIONS": {
+            "object_parameters": {"CacheControl": "max-age=31536000"},  # 1 year for static
+        },
     },
 }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In tcf_core/settings/base.py around line 76, the global AWS_S3_OBJECT_PARAMETERS
is set to {"CacheControl": "max-age=31536000"} which will apply a 1-year cache
to all S3 backends (including media); remove or avoid a global
AWS_S3_OBJECT_PARAMETERS and instead set cache-control per backend: keep the
long cache for the staticfiles S3 backend (assign AWS_S3_OBJECT_PARAMETERS or
equivalent on the static storage config only) and create a separate media S3
config used by DEFAULT_FILE_STORAGE with a safe cache header (e.g., no-cache /
max-age=0 / must-revalidate) so user uploads are not aggressively cached. Ensure
DEFAULT_FILE_STORAGE is pointed at the media backend and STATICFILES_STORAGE at
the static backend so each backend uses its own S3 object parameters.

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: 1

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

76-76: Remove redundant global AWS_S3_OBJECT_PARAMETERS.

Since you're now using per-backend object_parameters in the STORAGES configuration (lines 92 and 98), the global AWS_S3_OBJECT_PARAMETERS is redundant and may cause confusion. The per-backend settings will override this global setting, but it's clearer to remove it entirely.

Apply this diff:

-    AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=31536000"}  # 1 year cache
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3b46944 and 9e1aa60.

📒 Files selected for processing (1)
  • tcf_core/settings/base.py (2 hunks)
🔇 Additional comments (3)
tcf_core/settings/base.py (3)

91-93: Good: Per-backend cache control for media files.

Setting a 1-day cache for media files in the default storage is appropriate for user-uploaded content. This correctly addresses the previous review concern about the global cache setting affecting media files.


96-96: Good: S3ManifestStaticStorage enables cache busting.

Switching to S3ManifestStaticStorage is the correct approach when using long cache times for static files. It appends content-based hashes to filenames (e.g., base.cssbase.a1b2c3d4.css), ensuring browsers fetch updated files after deployments despite the 1-year cache.


97-99: Good: 1-year cache appropriate for manifest-based static files.

The 1-year cache for static files is safe and effective with S3ManifestStaticStorage, which ensures updated files are fetched through filename changes. This configuration achieves the PR's goal of reducing client re-fetch frequency while maintaining cache freshness through content-based hashing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant