J
J
John Didact2020-08-03 18:48:28
PHP
John Didact, 2020-08-03 18:48:28

Where to store sessions? SQLite? MySQL? memcached? Redis? FS?

I store sessions in FS. For authorized users - in one folder, for unauthorized users - in another. In the folder unauthorized by the daemon, I go and delete the old sessions. It seems to be normal ... But I decided to look into the future: there are directories with unauthorized, especially with authorized sessions, packed to the brim! I saw a lot of disadvantages in this: reading the directory will become more difficult, I can exceed the limit on the number of files (I'm on shared hosting, since I have neither money nor brains for more).
In general, I decided that I needed to look for another repository. Read more about how to store...

What conclusions did I draw for myself? From worst to best in my opinion:

1) Хранить дальше в ФС
Минусы: операция открытия и чтения файла, как я понял, слегка дороговата… Ограничение файлов, сложность чтения огроменного каталога.
Плюсы: лёгкая реализация и надёжность сохранности.
2) MySQL
Минусы: я вообще хочу минимизировать запросы к MySQL. В MySQL храню, в основном, большие данные, которые не редко меняются или данные, которые потом храню в сессии. Опять же, как я понял, множество запросов к мускулу и получение результа дольше, чем чтение файла (я не говорю, что соединение с мускулом дольше, чем открытие и чтение файла… я именно про запросы и получение результа). Соединение с сервером БД может по какой-либо причине оборваться.
Плюсы: лёгкая реализация, надёжность сохранения сессии (если считать, что соединение всегда установится)
3) Memcache/Redis
Ну об этих штуках я мало что знаю… Говоря про кэш, раньше я хранил кэш тупо в ФС. Вчера понял, что это не Найс и на кэш написал класс, который принимает данные кэша и класс сам определяет, по мере доступности, где его сохранить, в Memcached, SQLite или в ФС. С Memcached я ещё особо не разобрался. На своем хостинге я не нашел класс Memcache, зато нашёл Memcached, его нужно было принудительно врубить… От куда взять сервер - я вообще без понятий)) Написал localhost с портом 11211… хз, вроде работает. С Redis'ом вообще ещё даже не ознокамливался. Ну это на потом. С кэшем я разберусь… Хотел бы в ОП хранить его, и буду. Но вот сессии…
Минусы: я пока ещё не разобрался с Memcached и это минус (скорее минус мне, но всё же). Как я понял, Memcached может упасть в любой момент. И там уже нужно поднапречься, чтобы создавать дампы, цепочки северов и прочее. Жизнь и без этого сложна, не хочется ещё больше её усложнять. В Memcached я буду хранить кэш, который не критично потерять, не хотелось бы всё это смешивать в одной области.
Плюсы: всё довольно быстро (как я понял)
4) SQLite
Как по мне, в соотношении надёжный / быстрый / лёгкий - самый молодец!
Минусы: почти те же, что и у ФС за исключением размера каталога и кол-ва файлов. На счёт открытия и чтения файла я не вдавался в подробности, как там всё это происходит. Но, думаю, тоже так же, как обычное открытие и чтение. Здесь это не критично. Мне более важны размер каталога и кол-во файлов. Вот на счёт блокировки файла таблицы я ещё не совсем понял. Если 100 пользователей одновременно зайдут на сайт, что произойдёт? Они в очередь встанут или сломаются? За тайм-аут не выйдут?
Плюсы: легко, быстро…

Ещё читал про хранение на стороне клиента в куках, зашифровано, с ключом и т.д. но мне вообще это не подходит. Я не доверяю данным клиента, даже id сессии из Кук проверяю. Да и ограничение данных в куках. В общем, от этого сразу отказался.

I preferred SQLite. What stones are waiting for me? And what would you recommend for storing sessions, except for the FS?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
FanatPHP, 2020-08-03
@JohnDidact

Store in muscle.
Files are really the worst option. Sarah Golemon, in a recent response to a similar question, wrote

File storage is only a default because the runtime doesn't know in advance what database engine or credentials you're going to use unless you tell it. So... ya know.... tell it.

That is, the files are out of desperation, and in a good way PHP would be stored in the database, but simply does not know which one and how to connect to it.
Radishes and memcache are cache, not storage. Think about what a cache is and what it is used for. And is the cache suitable for storing sessions.
You are right about whining. Same files, side view.
And about the muscle is very funny. Some kind of general database fear. Whence this "I generally want to minimize requests to MySQL"? What kind of nonsense about "the connection can break"? And how can you even compare the performance of a file on disk that opens with every request, with a daemon that holds all the data in memory and gives it over the socket?

R
Roman Kitaev, 2020-08-03
@deliro

SQLite and FS - absolutely not suitable if the application will scale
DB servers (MySQL / PostgreSQL / etc.) - reliable but slowest option
In-memory database (Redis / memcached) - excellent option, of all the above, the most productive, but you can to rest against the
Signed Cookie Session RAM (and its special case - JWT) - an option not described by you, the most economical in memory and disk and the most productive. The session is stored directly in the cookie. The data itself is serialized, for example, with JSON and compressed, for example, with gzip (but you can also take msgpack + lzma, whatever you like). After that, so that the user (or hacker) does not change the cookie at will, it is signed, for example, with HMAC + any crypto-resistant hash function
Of the pros : 0 bytes of busy RAM (except for the moment the request is executed), 0 bytes of disk space occupied, no dependencies on databases sent on each request, there is a limit on the size of the data in the session, because the data must fit into the cookie, including the signature and delimiters. But for the sake of experiment, I managed to shove the first chapter of War and Peace condensed into such a session before hitting the limit.

S
Sergey Pugovkin, 2020-08-04
@Driver86

(I'm on shared hosting because I don't have the money or brains for more).

If the project is small, then the files will be enough. If auto-cleaning is not configured, configure it.
Otherwise, you can use Redis. It's a database, not a cache like memcache is.
You are right about whining. Same files, side view.

It's more about MySQL. Sqlite is only one file and the problem here can only be with horizontal scalability (for example, when clustering a project).
And it's not the best idea to store frequently deleted/changed data in the database - this will lead to its defragmentation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question