I'm working on a server, which you can pass some form of authentication as input (like connection string) and it will connect you to your database. So the DB connection is going to be dynamic. There can be multiple users at the same time, connecting to different databases.
What I'm wondering is, is there a preferred way of managing the connections? Should the DB Client be stored in memory after authentication, so each user can immediately retrieve it using their session data / and execute queries against it? Or should I close / reopen the connection every time the user wanted to do something. I can use JS to figure out if the user is active on the page / or left and get rid of the connection object using users' state as well.
Approach 1
- User signs in to our web application.
- User enters the credentials to database (like the connection string)
- Server authenticates against the DB and we now have the connection client object. We keep it in a dictionary mapped to user id.
- User wants to run a query. We determine the user id from the request, fetch the client from the memory and run the query.
- When user leaves the page, we detect it through JS (
unload
event) send a request / or socket packet to server and close the client + remove it from the dictionary.
Approach 2
- User signs in to our web application.
- User enters the credentials to database (like the connection string)
- Server authenticates against the DB and we just confirm that connection worked. We don't keep the client object in memory.
- User wants to run a query. We re-connect to the database, run the query and close the connection. No dictionaries are kept in memory, we reconnect every time the user wants to do something.
Further design clarifications:
- This is a single page application.
- Although we don't have load balancing at the moment, depending on the user load we might end up adding it.
- We can assume only 1 user is going to connect to a particular database through this system.
- Sessions are managed through cookies and server side code.
- We don't really care about the distance between the SQL and our server. Given that it should be able to connect to any-given SQL - there isn't a favourable location unless it's fully distributed and we're not doing that at this stage.
What do you think?
SET SESSION AUTHORIZATION bob
/SET SESSION AUTHORIZATION DEFAULT
?