Today's curiosity resolution topic is Does Django's request.session.get() cause performance degradation? 🎯
While developing in Django, we often call request.session.get('key_name')
multiple times, right? But suddenly, I had this thought.
"If sessions are ultimately stored in the database, does a DB query occur every time
request.session.get()
is called?""Or does Django have some smart processing that prevents additional queries?"
To solve this curiosity, I delved deep into the SessionMiddleware source code in Django and confirmed through experiments. 🚀
1️⃣ How is request.session created in Django?
Let's find out when Django loads the session while creating the request object.
We usually fetch session data like this in a view function.
session_username = request.session.get('username')
However, if Django sends a DB query every time we use request.session.get('username')
, it could significantly impact performance, right?
🔍 Let's Look Inside Django!
In fact, Django pre-loads session data when a request comes in through middleware called SessionMiddleware
. During this process, a DB query occurs exactly once, and afterwards, the session data is maintained within the request object.
Looking at Django's SessionMiddleware
code, we see the following process.
class SessionMiddleware(MiddlewareMixin):
def process_request(self, request):
session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
request.session = self.SessionStore(session_key)
📌 Key Points!
- ✅ The session key (
session_key
) is obtained fromrequest.COOKIES
. - ✅ By calling
self.SessionStore(session_key)
, session data is fetched from the DB only once and stored in request.session. - ✅ Thus, even if
request.session.get()
is called multiple times in a view function, no additional DB query occurs! 🎯
2️⃣ Does request.session.get() Trigger a DB Query?
Now, let's return to the key question.
"When
request.session.get('username')
is called in a view, does a DB query occur?"
🚀 To conclude, calling request.session.get()
does not trigger additional DB queries.
The reason is simple.
✔ Django loads session data once when the request arrives and saves it in request.session
.
✔ So calling request.session.get()
retrieves data that’s already loaded in memory, hence no additional database querying is required.
The time when the session is actually fetched from the DB is only once at the beginning of the request. The SQL query executed at that time is as follows.
SELECT session_data FROM django_session WHERE session_key = 'xyz123' LIMIT 1;
In summary, ✅ even if request.session.get()
is called multiple times in a view, Django does not execute additional DB queries!
✅ The retrieval of data from DB occurs only once at the start of the request!
3️⃣ Do Queries Occur When Using Session Data in Templates?
"If session data is retrieved in the view and then passed to the template, does using it in the template also trigger additional DB queries?"
For instance, let's assume the session data is passed like this in the view.
def my_view(request):
session_username = request.session.get('username') # DB query occurs? ❌
return render(request, 'my_template.html', {'session_username': session_username})
And let's see how it’s used in the template.
<p>Logged in as: {{ session_username }}</p>
In this case, no additional DB query occurs either!
✔ session_username
is already the value fetched from request.session, so no additional DB lookup is needed when Django passes it to the template.
✔ Django manages request.session
like a memory cache, so it can be safely used in templates.
4️⃣ Will Changing Session Data Save to the DB?
"So what happens if I modify data like request.session['username'] = 'new_value'?"
🚀 In this case, the changes are saved to the DB, triggering additional DB queries!
If you change session data as below,
request.session['username'] = 'new_value'
Django saves the modified session data to the DB when sending the response. The SQL query executed during this time is as follows.
UPDATE django_session SET session_data = 'new_value' WHERE session_key = 'xyz123';
✔ Reading from the session does not trigger a DB query, but changing the session makes Django execute a query to save it in the DB.
5️⃣ Differences Based on Session Storage Method (Backend)
Django allows you to change the way sessions are stored (backend). Be mindful that the occurrence of queries may vary depending on the backend.
Session Backend | Description | Occurs DB Query? |
---|---|---|
django.contrib.sessions.backends.db |
Default DB-based session | ✅ Occurs once per request |
django.contrib.sessions.backends.cache |
Cache-based session (Redis, Memcached) | ❌ No DB queries |
django.contrib.sessions.backends.cached_db |
Cache + DB session (Queries DB if not in cache) | 🚀 Occurs if not in cache |
django.contrib.sessions.backends.signed_cookies |
Cookie-based session | ❌ No DB queries |
🚀 Thus, using cache
or signed_cookies
as backends can fetch sessions without DB queries. ✔ If performance is crucial, considering CACHED_DB_SESSION
is a good option too.
🎯 Conclusion
- ✅ Django pre-loads session data through
SessionMiddleware
at the start of the request and saves it in therequest.session
object. - ✅ Therefore, calling
request.session.get('username')
in a view does not trigger additional DB queries. - ✅ No additional DB queries occur when using session data in templates.
- ✅ However, changing session values results in Django saving the modified data to the DB when it responds.
- ✅ Depending on the session backend settings in Django, the occurrence of queries may differ. Using cache-based (
cache
orcached_db
) can reduce the DB load.
🔥 Next Episode Preview: When does the request
object disappear?
So when does the request
object disappear?
-
Does it still occupy memory after the request is finished?
-
Is it automatically cleaned up by the system, or do we need to manage it ourselves?
🚀 Next episode, we will explore the lifespan of Django's request
object and memory management! Stay tuned! 😃
Add a New Comment