Does my Django project need caching?

In the deployment checklist they included the hint on caching.
I wonder whether caching is always recommended in a Django project?
Or what are the thresholds/parameters to know whether to implement caching or not?

Currently my django project is only a minimal project with two forms and few static pages and pictures.
I don’t expect lot’s of traffic and I am planning to deploy it to Heroku or another free service for now - just to go through the deployment process once.
But in the long run the project as well as the traffic is meant to grow.

Is it recommended to implement caching right from the beginning or isn’t it a problem to implement it later (at a point where it might be more useful)?


Based on the source code of the SessionMiddleware I assume that caching doesn’t work by default in production, because self.SessionStore = engine.SessionStore always refers to the SESSION_ENGINE in the settings (which is not active in the default Django project).


When I deactivate the SessionMiddleware as described in How to use sessions, I get the following error:

django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application.
        HINT: Insert 'django.contrib.sessions.middleware.SessionMiddleware' before 'django.contrib.auth.middleware.AuthenticationMiddleware'.

In my understanding this means that I can decide to either deactivate the admin (somehow) or use activate the SessionMiddleware.
If so, do I then also need to configure the CACHES and the SESSION_ENGINE?

It really depends upon a lot of other environmental conditions.

By default, the session table is stored in the database. PostgreSQL already aggressively caches frequently used data in memory. My largest site (by number of users - about 5000 corporate individuals) works with a database that is effectively memory resident (~ 4 GB). We see no effective improvement by moving sessions to cache.
(And yes, it is easy to add and remove)

I can’t imagine any situation where you wouldn’t want the SessionMiddleware at all. But you don’t need to configure those items. In the absence of other configuration, it will use the database as the session store. You don’t need to configure CACHES or SESSION_ENGINE, SESSION_ENGINE by default is configured for ‘django.contrib.sessions.backends.db’.

(Side note: Defaults for settings are found in django.conf.global_settings. Those are the settings applied in the absence of having them set in the settings.py file.)

1 Like

Great, thank you for the insight in your own hands-on experiences.
Then I’ll probably use only the SessionMiddleware with the default settings for the beginning and maybe add additional caching later if needed.