Project

General

Profile

For a Wt REST webapp, what is the best way to handle DB session?

Added by Plug Gulp almost 5 years ago

Hi,

I am experimenting with using Wt REST API to query data from a DB using Wt DBO. There is a following statement in the Wt DBO tutorial(https://www.webtoolkit.eu/wt/doc/tutorial/dbo.html):

"The Session object is a long living object that provides access to our database objects. You will typically create a Session object for the entire lifetime of an application session, and one per user."

But for a REST API there is no concept of an application session, so what is the best way to manage the DBO session per user? Will the server require to maintain in memory a mapping between the user/API "key" and a DBO session?

Thanks and regards,

~Plug


Replies (2)

RE: For a Wt REST webapp, what is the best way to handle DB session? - Added by Roel Standaert almost 5 years ago

There really is no single best way.

The simplest (stateless) solution is to just create a new session for every request, and to use an SQL connection pool. You will then have the slight overhead of initializing a session every time (setting up mappings with mapClass). If performance is adequate when using that method, I would recommend you just do that.

Another (stateless) approach is to use thread local storage for sessions (so you have one Dbo session per thread). This is the approach used in the te-benchmark example.

If you're writing a stateful service, then a Dbo session per user session could be an option. This is indeed not a built-in feature of Wt, so you'd have to create your own user sessions (you could use WRandom::generateId if you need ids). You could keep a mapping in memory of user session to session information (including the Dbo session), with the appropriate thread synchronization (e.g. mutex locks). You'd also have to make sure those sessions are properly expired, though.

RE: For a Wt REST webapp, what is the best way to handle DB session? - Added by Plug Gulp almost 5 years ago

Thank you!

Because I am experimenting with REST and Wt, I think the first two options will be appropriate with REST.

Kind regards,

~Plug

    (1-2/2)