Postgres – vsetko, co si chtel vediet, ale bal sa spytat svojho seniora, aby si nevypadal ako jelito 09. Sesny.
Sesny su konexie do DB. Ked sa user/appka prihlasi do postgresu, master daemon sa forkne a vytvori novy backend proces. Sesna je vzdy jeden proces s vlastnym PIDom a standardna koneksna vyzerie priemerne tak 10MB pamate.
Jak listovat sessions
Zakladom pre prehlad sesns je systemova tabulka pg_stat_activity. Zhromazduje vsetky uzitocne info o procesoch, uzivateloch, casoch a stavu koneksny. Naprosto postacujuce v drtivej vacsine pripadov.
Info o procesoch sa da vyextrahovat aj zo sytemovej tabulky pg_stat_database, je tam stlpec numbackends (= pocet procesov), ale pozor pri pocitani, prikazy SELECT COUNT(*) FROM pg_stat_activity; a SELECT SUM(numbackends) FROM pg_stat_database; nedaju rovnaky pocet koneksns do DB, pretoze pg_stat_activity pocita aj wal senders, ktore su vlastne regulernou koneksnou v databazi. Tiz vezmi v uvahu, ze ked si lognuty cez psql, tak si vytvoril koneksnu, ktora je tam zapocitana…
Pokrocile dotazy na sesny
Kolko mam sesien a kolko z nich je v akom stave (idle, robia nieco…):
SELECT state, COUNT(*) FROM pg_stat_activity WHERE pid <> pg_backend_pid() GROUP BY 1 ORDER BY 1;
Dotaz, ktory zobrazi pocet max_sessions z konfu, pocet aktualnych sesns a pocet sesns rezervovanych pre superusera (postgres):
SELECT * FROM
(SELECT COUNT(*) used FROM pg_stat_activity) q1,
(SELECT setting::int reserved_superuser FROM pg_settings WHERE name=$$superuser_reserved_connections$$) q2,
(SELECT setting::int max_conn FROM pg_settings WHERE name=$$max_connections$$) q3;
Dalsie skvele SQL dotazy na sesny a vykon na depeszu…
Jak killovat sesions
Sesny sa nesmu kilovat cez OS (kill -15 PID), pretoze to zhodi cely server. Je obecne daleko lepsou praxou kilovat ich cez DB API adminskymi funkciami, nez “zvonka”. Typicky je to prikaz pg_terminate_backend(PID)
SELECT pg_terminate_backend(procpid) FROM pg_stat_activity
WHERE
— don’t kill my own connection!
pid <> pg_backend_pid()
— don’t kill the connections to other databases
AND datname = ‘DB_name’;
Uvedeny prikaz ma jednu necnost a tou je fakt, ze ak potrebujem mat databazu trvale odpojenu od sessions (napriklad ju alterujem), tak hned po po jeho zavolani mi vznikaju nove sessns a neda s tym pracovat. Prikaz pre uzavretie DB od pripojenia (sesien):
ALTER DATABASE db_name WITH ALLOW_CONNECTIONS = false;
Analogicky, ak potrebujem obmedzit DB len na urcity pocet sesien, tak:
ALTER DATABASE db_name WITH CONNECTION LIMIT 10;
pgbouncer
https://medium.com/futuretech-industries/ten-thousand-high-availability-postgresql-connections-for-35-mo-part-one-4b7a2d61c51e
Frajer
12 Mar 20 at 13:20
https://stackoverflow.com/questions/13236160/is-there-a-timeout-for-idle-postgresql-connections
dobo
2 Sep 20 at 14:40
prikaz na disblovanie novych koneksii pre konkretnu databazu:
UPDATE pg_database set datallowconn = false WHERE datname = ‘nazov databaze’;
dobo
26 Jan 23 at 13:07