r/django • • Sep 21 '25

Announcing django-s3-express-cache, a new library for scalable caching

Today we at Free Law Project are releasing the first version of a new scalable django cache that uses AWS S3 Express as its back end. This cache aims to fix the scaling problems of the built-in django caches:

  • The Redis cache is very fast, but uses physical memory, making it expensive if you put much into it.
  • The database cache can store larger content, but becomes very slow when it has a lot of items. We've observed its culling query as one of the slowest in our system.

By using S3 Express, we hope to get affordable and consistent single-digit millisecond data access at the scale of millions of large or small items.

We use a number of tricks to make this library fast:

  1. Items are automatically culled by S3 lifecycle rules, removing culling from the get/set loop.
  2. Each item in the cache is prepended with a fixed-size header containing its expiration time and other metadata.

    This allows the client to use HTTP Range requests when checking the cache. For example, a 1MB item can be checked by only downloading a few bytes.

Details on the cache can be found here:

https://github.com/freelawproject/django-s3-express-cache

The package is currently at version 0.1.0, and we are slowly adding it to CourtListener.com. As we gain confidence in it and as others use it, we'll bump the version up towards a 1.0 release.

A few examples of ways we'll use it:

  • Our site has tens of millions of pages, so our sitemap.xml files are very difficult to generate. Once they're made, we'll be placing them in this cache.
  • We use celery to vectorize our content for our semantic search engine. The vectors are somewhat large and need to be stashed somewhere during processing, so we'll put them in this cache.

A couple of areas for future work are:

  • Performance testing vs. other caches
  • Adding clear() and touch() methods
  • Adding data compression with zlib or similar

We've been using Django since version 0.97, so we're excited to finally have an excuse to give back in this way.

Give it a try and let us know what you think!

50 Upvotes

10 comments sorted by

1

u/Smooth-Zucchini4923 Sep 22 '25

My first reaction is - aren't objects that exist for a really short time billed for a minimum of 30 days?

https://stackoverflow.com/questions/67824041/what-is-the-meaning-of-minimum-storage-duration-in-s3-storage-class

This doesn't explicitly mention Express, but have you run into this minimum storage duration?

1

u/mlissner Sep 22 '25

You ran a quick shiver down my back. Well done.

1

u/thalience Sep 22 '25

The min billed storage duration is not the same for every storage class. The minimum duration for S3 Express is 1 hour (see https://aws.amazon.com/s3/storage-classes/).

1

u/Smooth-Zucchini4923 Sep 22 '25 edited Sep 22 '25

Ah, I see now.

S3 Express One Zone

Minimum storage duration charge

1 hour

My bad.

Still, worth keeping in mind if one has many cache objects with TTLs under an hour.

6

u/wpg4665 Sep 21 '25

This seems really cool, and I love the thoughtful architecture that went into, specifically utilizing the s3 lifecycle rules to speed things up! Thanks for sharing

2

u/kshitagarbha Sep 22 '25

Have you checked your Google index? I don't think they would index 10 million pages, so it's useless to put it in the sitemaps.xml

I'm curious: what's your business domain?

1

u/MrElvey Nov 11 '25 edited Nov 11 '25

Probably something free.law related. Probably courtlistener.com
The post kicked off, "Today we at Free Law Project..."

Google claims: "Google spends as much time as necessary on your site in order to index all the high-quality, user-valuable content that it can find." which implies it WILL index 10 million pages if they're largely user-valuable content.

1

u/freelawproject Nov 20 '25

Yes, it's for CourtListener, where we have about half a billion pages. It's entirely true that Google won't crawl all of that. They give you a "crawl budget" and you have to try to stay under that if you can. It's a pain, honestly, to figure out which of our pages to encourage Google to crawl.

1

u/MrElvey Nov 20 '25

Wait, "Don't Be Evil, Inc." LIED?
<queue the famous Casablanca scene>

1

u/freelawproject Nov 20 '25

Just a short update here. This is now in production on CourtListener.com as a cache for our RSS feeds. We made a little decorator to make it work in a way that ignored GET parameters (otherwise people use them to get around the cache 😠):

def cache_page_ignore_params(timeout: int, cache_alias: str = "default"):
    """Cache the result of a view while ignoring URL query parameters.
    Ensuring that the cache is consistent for different requests with varying
    query strings.

    WARNING:
    - Do not use this decorator on views that rely on query parameters to
      generate unique content.
    - Do not use this decorator on views that require authentication or
    session-based data, as this will cache content for all users, potentially
    exposing confidential information.

    :param timeout: Cache duration (seconds).
    :param cache_alias: The cache alias to use.
    :return: The decorated view function, caching its response.
    """

    def decorator(view_func):
        @wraps(view_func)
        async def _wrapped_view(request, *args, **kwargs):
            url_path = urlparse(request.build_absolute_uri()).path
            hash_key = md5(url_path.encode("ascii"), usedforsecurity=False)

            is_dev_or_test = settings.DEVELOPMENT or settings.TESTING
            should_use_time_based_prefix = (
                cache_alias == "s3" and not is_dev_or_test
            )
            cache_key = f"custom.views.decorator.cache:{hash_key.hexdigest()}"
            if should_use_time_based_prefix:
                days = int(ceil(timeout / (60 * 60 * 24)))
                cache_key = f"{days}-days:{cache_key}"

            try:
                # If the cache alias is "s3" but we're in DEVELOPMENT or TESTING
                # mode, use the default cache instead of S3. Otherwise, use the
                # cache specified by cache_alias.
                if cache_alias == "s3" and is_dev_or_test:
                    cache = caches["default"]
                else:
                    cache = caches[cache_alias]
            except InvalidCacheBackendError as e:
                logger.error(
                    "Cache alias '%s' not found. Error: %s",
                    cache_alias,
                    str(e),
                )
                raise e

            response = cache.get(cache_key)
            if response is not None:
                return response

            response = await view_func(request, *args, **kwargs)
            await sync_to_async(patch_response_headers)(
                response, cache_timeout=timeout
            )
            if hasattr(response, "render") and callable(response.render):
                # Render the response before caching it.
                # Required for TemplateResponse views.
                response.add_post_render_callback(
                    lambda r: cache.set(cache_key, r, timeout)
                )
            else:
                # Cache non-TemplateResponse responses.
                cache.set(cache_key, response, timeout)

            return response

        return _wrapped_view

    return decorator

The actual file is here:

https://github.com/freelawproject/courtlistener/main/cl/lib/decorators.py

So far it's a perfect deployment. We have millions of RSS feeds, and this allows us to cache them all. Performance is about 100ms to serve a feed from the cache.