Re: using postgresql for session - Mailing list pgsql-general

From Jonathan Vanasco
Subject Re: using postgresql for session
Date
Msg-id 5D401609-D0CE-4D53-A45F-B762B6BF07FA@2xlp.com
Whole thread Raw
In response to using postgresql for session  ("john.tiger" <john.tigernassau@gmail.com>)
Responses Re: using postgresql for session  (Tiger Nassau <john.tigernassau@gmail.com>)
List pgsql-general
On Oct 7, 2015, at 11:58 AM, john.tiger wrote:

> has anyone used postgres jsonb for holding session ?  Since server side session is really just a piece of data, why
botherwith special "session" plugins and just use postgres to hold the data and retrieve it with psycopg2 ?  Maybe use
sometrigger if session changes?    We are using python Bottle with psycopg2 (super simple, powerful combo) - are we
missingsomething magical about session plugins ? 

I previously used TEXT or BLOB for holding session data, and pickled the data.  I can't remember.

If you're going to use PostgresSQL for the session, the big performance tip is to use partial index on the session key
(assumingit's an md5-like hash). 

So you'd want a table that is something like this:

    CREATE TABLE session(
        session_id VARCHAR(32) PRIMARY KEY,
            session_data TEXT
    );
    CREATE INDEX idx_session_partial ON session(substr(session_id , 0,5))

Then query like this

    SELECT * FROM session WHERE session_id = :session_id AND substr(session_id, 0, 5) = :session_id_substring ;
    SELECT * FROM session WHERE session_id = :session_id AND substr(session_id, 0, 5) = substr(:session_id, 0, 5) ;

That will get the planner to use the partial index first, before using the session_id index.  Depending on how many
itemsare in your table, it can make your SELECTS several orders of magnitude faster. 

As for session plugins -- a lot of people in the  web frameworks community are abandoning server side sessions for
clientside sessions.  They are generally easier to handle state across clusters and data centers.  Some server side
session-likedata is still needed, but it's often assembled from data in the client side. 

Most of the Python session plugins I've used have some sort of status check coupled with a cleanup function/middleware
componentto see if the object has changed at all.  This way UPDATES only occur when needed. 

FWIW, I ended up migrating our sessions into redis.  We already had redis running on the cluster, and offloading it got
alot more performance our Postgres without scaling our hardware.   There just isn't much of a reason for having pg
managea simple KV store. 



pgsql-general by date:

Previous
From: Ramesh T
Date:
Subject: postgres function
Next
From: "David G. Johnston"
Date:
Subject: Re: postgres function