NAME

Web::Session::PgJSON - Add index and search methods to Apache::Session for PostgreSQL, using a JSON column

SYNOPSIS

Create table:

CREATE UNLOGGED TABLE sessions (
    id varchar(64) not null primary key,
    a_session jsonb
);

UNLOGGED tables are lost on a crash and not replicated to standby servers: see "POSTGRESQL TUNING".

Optionally, add indexes on some fields. Example for Lemonldap::NG:

CREATE INDEX uid1 ON sessions USING BTREE
  ( (a_session ->> '_whatToTrace') text_pattern_ops );
CREATE INDEX  s1  ON sessions ( (a_session ->> '_session_kind') );
CREATE INDEX  u1  ON sessions ( ( cast(a_session ->> '_utime' AS bigint) ) );
CREATE INDEX ls1  ON sessions
  ( ( cast(a_session ->> '_lastSeen' AS bigint) ) );
CREATE INDEX rt1  ON sessions
  ( ( cast(a_session ->> '_oidcRtUpdate' AS bigint) ) );
CREATE INDEX ip1  ON sessions USING BTREE
  ( (a_session ->> 'ipAddr') text_pattern_ops );

searchOnExpr() uses LIKE 'prefix%' queries: unless the database uses the "C" collation, PostgreSQL can't use a plain btree index for them. The text_pattern_ops operator class lets the same index serve both = and prefix LIKE searches. Note that a search starting with a * wildcard can never use a btree index.

deleteIfLowerThan() can use u1 and ls1 indexes only if they are declared exactly as above. ls1 is needed when Lemonldap::NG "timeoutActivity" is used: sessions purge then deletes sessions whose _utime or _lastSeen is too old, and an OR with a non indexed side forces a full table scan.

rt1 is useful when OpenID Connect relying parties have a refresh token activity timeout: sessions purge then calls searchLt() on _oidcRtUpdate, which can use this index only if it is declared exactly as above.

Avoid a global GIN (a_session jsonb_path_ops) index: queries of this module don't use the @> operator, so it is never used. Measured on 300,000 realistic Lemonldap::NG sessions, it took 167 MB (versus 15 MB for the uid1, s1, u1 and ip1 btree indexes above) and made updates about 3 times slower.

A single GIN index can replace the btree indexes used only for equality searches (like s1), but it is much bigger and slows down updates: see "GIN INDEX".

Don't set Index: any field can be searched. Use it like the other backends of Web::Session. Web::Session::Postgres is an alias of this module.

DESCRIPTION

Web::Session provides some class methods to manipulate all sessions and add the capability to index some fields to make research faster.

Web::Session::PgJSON implements it for PosqtgreSQL databases using "json" or "jsonb" type to be able to browse sessions. The GinIndex option requires "jsonb".

GIN INDEX

Instead of one btree index per searched field, one GIN index can serve searchOn() on any field:

CREATE INDEX gin1 ON sessions USING GIN (a_session jsonb_path_ops);

It is used only if GinIndex is set in the arguments (for Lemonldap::NG, in sessions storage options):

GinIndex => 1,

searchOn() then adds a a_session @> '{"field":"value"}' condition, the only kind of query this index can serve. The @> operator and the jsonb_path_ops operator class exist only for "jsonb": with a "json" column, the index can't be created: GinIndex is then ignored, with a warning, and searchOn() falls back to the query used without the option. The warning is emitted once per database handle (so once per process and connection, also for each connection of the pool) and table. To use the index, convert the column first:

ALTER TABLE sessions ALTER COLUMN a_session TYPE jsonb
  USING a_session::jsonb;

This rewrites the whole table under an ACCESS EXCLUSIVE lock: sessions are blocked during the conversion. It fails if a session contains \u0000 (accepted by "json", refused by "jsonb"). The column type is cached per database handle and table: processes already connected must be restarted (or reconnect) after the conversion, else they keep ignoring GinIndex (pooled connections are renewed after MaxLifetime, see below).

Results are the same as without GinIndex:

  • Containment is type sensitive while the ->> operator used without GinIndex is not: searching 123 finds both the string "123" and the number 123 (like _utime). So a value that looks like a JSON number or boolean is searched in both forms, with two index scans combined by a BitmapOr.

  • The ->> comparison is kept to filter the rows found by the index: for example, {"k":1.50} contains {"k":1.5} but searching 1.5 must not find 1.50.

  • Numbers beyond PostgreSQL numeric limits (more than 131072 digits before the decimal point or 16383 after) can't be stored in "jsonb": such values are searched as strings only.

  • Values starting with [ or { (possible text of JSON arrays and objects) and values or field names containing a NUL character are searched without the GIN index.

Measured on PostgreSQL 17 with 300,000 realistic Lemonldap::NG sessions (391 MB table):

  • the GIN index takes 167 MB, versus 15 MB for the uid1, s1, u1 and ip1 btree indexes above;

  • searchOn() lookups through the GIN index or through a btree index are comparable, well under 1 ms. The gain is on fields without btree index: 0.04 ms instead of a 30 ms full table scan;

  • updating 30,000 sessions takes 6.3 s with the GIN index, versus 1.9 s without it (about 3 times slower). The 4 btree indexes above were present in both runs.

Sessions are updated often (_utime, _lastSeen), so this write cost usually outweighs the lookup gain. The GIN index is interesting when searchOn() is used on many fields that have no btree index. Enabling GinIndex without the index only adds useless conditions.

The GIN index doesn't help searchOnExpr() (LIKE), deleteIfLowerThan() (< comparisons, and not rules that must also match sessions without the field) nor get_key_from_all_sessions(). Keep the uid1, u1, ls1 and ip1 btree indexes above alongside it; s1 is not needed anymore. PostgreSQL may still prefer a btree index on the searched field, or a full scan for a frequent value like _session_kind = 'SSO'.

deleteIfLowerThan()

Sessions are deleted by batches, each batch being its own statement (autocommit), to avoid one huge transaction when a purge removes hundreds of thousands of sessions (WAL spike, long locks, replication lag):

DELETE FROM sessions WHERE id IN
  (SELECT id FROM sessions WHERE <rule> LIMIT n)

until a batch deletes less than n rows. The WHERE expression is the same as for a single statement, so the indexes described above are still used by the sub-select. n is $Web::Session::_common::BatchSize (1000 by default, accepted values: 1 to 1000000), the same variable that sets the size of the batches of get_key_from_all_sessions().

The return value is unchanged: (1, $deleted) in list context, 1 in scalar context. If a batch fails, the error is printed on STDERR and (0, $deleted) is returned in list context (0 in scalar context), $deleted being the number of sessions removed by the batches already executed, which stay committed (as Web::Session::LDAP does). The first value stays false, so a caller such as the Lemonldap::NG purge still sees the failure and falls back to its slower purge. This also applies to Web::Session::Postgres aliases and Web::Session::Patroni.

searchLt() and searchGt()

# Sessions whose _utime is lower than $time
my $hash = Web::Session::PgJSON->searchLt( $args,
    '_utime', $time, 'uid' );

searchLt() and searchGt() take the same arguments and return the same data as searchOn(): sessions whose field is lower (or greater) than the given value, which is excluded. The value must be a number (12, -12 or 12.5): otherwise nothing is returned and an error is printed on STDERR. Spaces around the value are ignored.

Fields are compared in SQL as deleteIfLowerThan() does (cast(a_session ->> 'field' AS bigint)): an expression index declared exactly as u1 or rt1 above is used with an integer value. As for deleteIfLowerThan(), the query fails if it reads a session where this field is not an integer (such an index refuses to store it): searchLt() and searchGt() then print the error on STDERR and compare all sessions in Perl, see "ERRORS" in Web::Session.

Sessions without the field are never returned. This differs from the Perl fallback of Lemonldap::NG, where a missing field is compared as 0: searchLt() would then return nearly all sessions. Lemonldap::NG doesn't need them: its sessions purge ignores sessions without _oidcRtUpdate.

Persistent connection

Database connections are kept open between sessions, managed by the connection pool described below. With Commit => 0 or KeepConnections => 0, sessions use the handle shared by the sessions of the process, like the other SQL backends, see "PERSISTENT DATABASE CONNECTIONS" in Web::Session. Set noreuse => 1 to open and close one connection for each session instead.

Connection pool (KeepConnections)

By default, sessions use a pool of connections: each process keeps up to MaxIdle idle connections per data source (DataSource and UserName), and lends each one to a single tied session at a time. The pool is not used with Commit => 0, with noreuse or with a Handle.

Class methods (searchOn(), searchOnExpr(), searchLt(), searchGt(), get_key_from_all_sessions() and deleteIfLowerThan()) called with the same arguments use the same pool: each call borrows a connection and gives it back when it returns. A process that uses both sessions and class methods (for example a Lemonldap::NG portal, whose SingleSession feature calls searchOn(), or the sessions purge, which calls deleteIfLowerThan()) thus doesn't keep one more connection for the class methods. The rules of the pool apply to these connections too: a connection that met an error is closed, expired ones are renewed, a child process doesn't use those of its parent.

A callback given to get_key_from_all_sessions() runs while the call holds its connection: if it ties a session or calls a class method, they get another connection of the pool (or open one), never the one of the running call. The connection is given back even if the query or the callback dies. Each nesting level holds one more connection while it runs, and the pool sets no limit: a callback that calls get_key_from_all_sessions() again, or keeps several sessions tied, needs as many connections at once. Keep callbacks flat (collect the ids, then work on them after the call) when the server has a low max_connections.

Without the pool (Commit => 0, KeepConnections => 0 or noreuse), class methods use the handle cached by DBI connect_cached(), as before. They never use the Handle argument.

Why a pool rather than the DBI connect_cached() handle used by the other SQL backends:

  • Two sessions tied at the same time in a process (for example a Lemonldap::NG session and its persistent session) never share a connection, and so never a transaction. With a shared handle, they share its transaction (AutoCommit off): untying one of them also commits (or rolls back) the changes already done in the other.

  • Error handling: a connection that met an error is closed, never lent again. For example, after a failover behind a virtual IP, a connection to the former primary still answers ping() but every write fails.

  • Timeouts: a connection idle for too long is closed without a ping(), which could wait for a TCP timeout on a connection dropped by a NAT or a load balancer; a connection is renewed after a maximum lifetime.

  • Fork safety: connections are opened with AutoInactiveDestroy and belong to the process that opened them. A child created by fork() neither uses nor closes the connections of its parent, even one that was lent when it forked.

Options:

KeepConnections

Set KeepConnections => 0 to disable the pool and get back the previous behaviour: the handle cached by DBI connect_cached(), shared by the sessions of the process, with AutoCommit off and a transaction committed at untie. Accepted values: 0 (or '0') disables the pool; a missing, undef or empty value keeps the default (enabled); any other value enables it. Strings such as '0.0', 'off' or 'false' are not 0 and so enable the pool: use 0.

MaxIdle

Idle connections kept per process and data source, 4 by default. 0 closes each connection at untie. Size the max_connections of the server for all the processes: each one keeps up to MaxIdle idle connections, plus one per session tied at the moment. For example, 3 servers with 50 Apache or FastCGI workers each and the default MaxIdle may keep 3 * 50 * 4 = 600 connections open, more during peaks. Lower MaxIdle (1 is enough when a worker handles one request at a time), or put a pooler in front of the server (see "Connection poolers (PgBouncer)").

IdleTimeout

Seconds: a connection idle for longer is closed instead of being lent (without a ping()), 120 by default. Adding keepalives_idle to the DSN also helps detect dead connections.

MaxLifetime

Seconds: an older connection is closed when it is given back, 3600 by default.

On these connections each statement is its own transaction (AutoCommit on): no session is locked, so a transaction around a tie protected nothing. Expired idle connections are closed when another connection is given back. A connection given back recently is lent without a round trip; an older one is checked with ping().

Commit is on by default (as with Web::Session::Patroni): a missing or empty Commit commits the writes, a session isn't rolled back at untie for lack of this option. With Commit => 0, changes are rolled back at untie, which the pool can't do: the store then keeps AutoCommit off on the shared handle. With a Handle, the caller owns the transaction: Commit is used as given (not set means not committed), as with Apache::Session::Postgres.

A new session is written once. Without the pool, as with Apache::Session, the tie of a new session inserts it with its empty data, and its untie updates it with its data: two writes, the second one a new row version and an entry in each index. With the pool, the INSERT waits for the untie and writes the data then; a session untied unmodified is inserted at untie (one still tied when the program ends is inserted by an END block, before the global destruction; a child process created by fork() leaves those of its parent to it), and a session deleted in its own tie is never written. The connection is still taken when the session is tied, so an unreachable database still makes the tie fail. When the id of the new session is given by the caller (setId, as Lemonldap::NG does), the tie checks that no session has it, and dies if one does, as the INSERT at tie does without the pool. If another process inserts this id between the tie and the untie, the INSERT fails: it is reported as a failed update (an explicit save() dies; at untie, Apache::Session doesn't propagate the error, DBI warns and the INSERT is tried again when the store is freed, with a warning if it fails again), and the other session is left untouched, also when the new one is deleted in its tie. Until its untie, a new session can't be read nor found by another process. Web::Session::Patroni doesn't defer the INSERT: it inserts a new session when it is tied, then updates it at untie.

Example with Lemonldap::NG (the pool is used, no option needed):

globalStorage        => 'Web::Session::PgJSON',
globalStorageOptions => {
    DataSource => 'dbi:Pg:dbname=sessions;host=db;keepalives_idle=30',
    UserName   => 'lemonldap',
    Password   => 'secret',
    TableName  => 'sessions',
    Commit     => 1,
},

Add KeepConnections => 0 to these options to get back the shared connect_cached() handle, or noreuse => 1 to open and close a connection for each session.

Web::Session::Patroni sessions use this pool too, keyed by the DSN of the primary node found through the Patroni API, see "Connection pool" in Web::Session::Patroni. Its class methods don't: they keep the connect_cached() handle, see "Class methods" in Web::Session::Patroni.

POSTGRESQL TUNING

Use "jsonb"

Prefer jsonb to json. A json column stores the text as received, so each ->> is evaluated by parsing the document again, for each row read: searches on a field without index, sessions purge, get_key_from_all_sessions() and so on. jsonb is stored in a decomposed binary form and doesn't need this parsing. Expression indexes (u1, s1... above) work with both types, but GinIndex requires jsonb. jsonb refuses the \u0000 character that json accepts: to convert an existing table, see the ALTER TABLE command (and its lock and failure cases) in "GIN INDEX".

Updates and autovacuum

Sessions are updated often (_utime, _lastSeen). In PostgreSQL, each UPDATE creates a new version of the row and leaves the old one as a dead tuple until (auto)vacuum removes it. Purge also leaves dead tuples. Moreover PostgreSQL can make an update HOT (heap-only tuple, the indexes are not touched) only if the columns used by the indexes keep the same stored value: it compares the column values, it doesn't evaluate the indexed expressions. The expression indexes above all use a_session, so an update that changes the session (_utime, _lastSeen...) is never HOT: it adds an entry to each index, including the primary key. This is also why the number of indexes directly drives the update cost (see the measures in "GIN INDEX"): keep only the indexes you really use.

For the same reason, lowering fillfactor (which leaves free room in pages for HOT updates) brings little here as soon as the table has expression indexes on a_session: only updates that write the session back unchanged can be HOT. It may help for a table that has only its primary key.

A busy sessions table is better vacuumed more often than the default (20% of dead rows) allows. Per-table settings can be used without changing the configuration of the other tables:

ALTER TABLE sessions SET (
    autovacuum_vacuum_scale_factor  = 0.02,
    autovacuum_analyze_scale_factor = 0.05,
    autovacuum_vacuum_cost_limit    = 1000
);

The scale factors make autovacuum start after 2% of dead rows (5% of changes for statistics) instead of 20% (10% for statistics). A higher autovacuum_vacuum_cost_limit (by default the global vacuum_cost_limit, 200) lets each run work faster, at the price of more I/O. These values are a starting point: check n_dead_tup, last_autovacuum and the table size in pg_stat_user_tables and adjust.

UNLOGGED table

An UNLOGGED table isn't written to the write-ahead log: writes are faster, but

  • the table is emptied after a crash or an unclean shutdown (a clean restart keeps it): all users have to authenticate again;

  • it isn't replicated to standby servers (and can't be read on a standby). After a failover (for example with Web::Session::Patroni), the new primary has an empty sessions table.

If sessions must survive a crash or a failover, create a normal table (or convert it with ALTER TABLE sessions SET LOGGED, which rewrites the table). You then pay the WAL volume of the frequent updates, on the primary and on each replica.

Connection poolers (PgBouncer)

DBD::Pg uses server-side prepared statements by default (pg_server_prepare). With PgBouncer in transaction pooling mode, the server connection may change between two statements, so a statement prepared earlier can be missing (prepared statement "dbdpg_p..." does not exist). PgBouncer 1.21 and later can track them if max_prepared_statements is set to a non-zero value; with older versions, or without it, disable server-side prepared statements. The module gives DataSource to DBI->connect() as is, so the attribute can be set in the DSN, using the DBI syntax for attributes:

DataSource => 'dbi:Pg(pg_server_prepare=>0):dbname=sessions;host=pgbouncer',

Without a pooler in transaction mode, keep the default (prepared statements save parsing time). Note that the connection pool described in "Connection pool (KeepConnections)" already avoids reconnecting for each session: a pooler is mostly useful to limit the total number of connections when many processes (each with up to MaxIdle connections) use the same server.

Detecting dead connections

A connection broken without being closed (firewall or NAT timeout, host down, failover) is detected by the kernel only after a long time by default (on Linux, 2 hours before the first keepalive probe). libpq parameters can be set in the DSN to detect it sooner on TCP connections:

DataSource => 'dbi:Pg:dbname=sessions;host=db;'
            . 'keepalives_idle=30;keepalives_interval=10;keepalives_count=3',

With these values, a dead peer is detected after about 30 + 10 * 3 = 60 seconds. Where supported, tcp_user_timeout (in milliseconds) also bounds the time to wait for unacknowledged data. This doesn't apply to Unix socket connections.

Purge

Lemonldap::NG removes expired sessions with a periodic purge that uses deleteIfLowerThan() and searchLt(). Indexes must be declared exactly as explained in "SYNOPSIS" (u1, ls1, rt1), else each run reads the whole table. A purge run after a long delay deletes many rows at once and leaves as many dead tuples for autovacuum: run it regularly, with the autovacuum settings above.

SEE ALSO

http://lemonldap-ng.org, Apache::Session::Postgres

COPYRIGHT AND LICENSE

2009-2026 by Xavier Guimard
2013-2025 by Clément Oudot
2019-2025 by Maxime Besson
2013-2025 by Worteks
2023-2026 by Linagora

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.10.1 or, at your option, any later version of Perl 5 you may have available.