Evgenii Legotckoi
Evgenii LegotckoiApril 18, 2022, 5:39 p.m.

Django - Tutorial 058. Database Growth Due to django_session Table

Lately, I have noticed that the fatal moment is approaching, when the disk space for the site on the hosting will catastrophically cease to be enough. And the database dump becomes incredibly huge, although there are no obvious prerequisites for this. The content size of the site isn't growing that fast, and the number of registered users isn't growing that fast either.

After examining the database, it was found that the size of the django_session table is just a gigantic almost 7 GB, and the size of the index also reaches almost 6.5 GB, despite the fact that the size of the database itself is 14 GB.

At the same time, the size of the second largest table is only 11 MB and this is a third-party application with a list of cities. And the size of the third table, which contains messages on the forum, is only 8 MB.

Accordingly, it was decided to figure out why this is happening and how to fix it.

Right now, I probably won’t reveal anything new to those who actively administer PostgreSQL databases, but for beginners and those who mainly deal with Django as a PET project, without professional use, the information may be useful.


How to check table size

https://evileg.com/ru/knowledge/article/add/#
To do this, simply execute the following query in the PostreSQL administration interface. And we get a sorted output of information on the database tables.

select table_name, pg_relation_size(quote_ident(table_name)), pg_size_pretty(pg_relation_size(quote_ident(table_name))) from information_schema.tables where table_schema = 'public' order by 2;

 forum_forumpost                        |          8290304 | 8096 kB
 cities_light_city                      |         11108352 | 11 MB
 django_session                         |       7225204736 | 6890 MB
(110 rows)

As you can see, in my case, the djang_session table has grown very much over the 6 years of the site's existence on the Django engine.
Thanks to DDOS visitors, the mechanism for creating session keys for all anonymous users, and the fact that by default PostgreSQL does not reduce the size of the database file even when deleting records.

And the size of the database can be seen like this

SELECT pg_size_pretty( pg_database_size('databasename') );
 pg_size_pretty 
----------------
 14 GB
(1 row)

Here is such an unpleasant size came out - 14 GB.

Deleting expired sessions

When a site is DDOSed or simply flooded with users, a huge number of sessions are created that are usually not deleted in Django, and the table index grows additionally.

Therefore, the first thing to do is to remove obsolete sessions. Django has the clearsessions command for this.

Therefore, in the console we activate the python environment of your project, go to the folder with your project and execute the following command.

python manage.py clearsessions

This will delete all old sessions. You can also schedule this command to run via cron.
For example, using the django-session-cleanup battery, it requires the use of celery .

Run the garbage collector

After you have completed the removal of old sessions, you need to free up the space occupied by the database.
This is necessary because the database's priority is performance over disk space savings. Thus, the database file grows due to the growth of the index, and the data has not been there for a long time. And also, by default, the garbage collector does not start by itself, for this you need to configure it to start on a schedule, for example, using a daemon.

But personally, I've done it manually so far. The garbage collector in PostgreSQL is started with the vacuum command.

vacuum FULL ANALYZE django_session;

After performing this operation, I check the size of the database again and see

SELECT pg_size_pretty( pg_database_size('databasename') );
 pg_size_pretty 
----------------
 494 MB
(1 row)

Now the database size is only 494 MB, which is good news.

It will be necessary over time to configure the garbage collector to run at least once a week, but more on that in the next article.

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

u
  • May 15, 2022, 7:58 a.m.
  • (edited)

А если хранить сессии в SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' ?
Интересно стало насколько безопасно хранить сессии в печеньках... стоит оно того или нет?)

Evgenii Legotckoi
  • May 15, 2022, 9:27 a.m.

Думаю, что скорее всего это будет менее безопасно, но на практике я не проверял.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
d
  • dsfs
  • April 26, 2024, 4:56 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
d
  • dsfs
  • April 26, 2024, 4:45 a.m.

C++ - Test 002. Constants

  • Result:50points,
  • Rating points-4
d
  • dsfs
  • April 26, 2024, 4:35 a.m.

C++ - Test 001. The first program and data types

  • Result:73points,
  • Rating points1
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks