0

Do I open and close a connection to a RethinkDB server on every HTTP request? I was reading a tutorial of the official examples. It describes an Express app and it basically looks like:

var app = express();
app.use(openConnection);
app.use(/* do stuff */);
app.use(closeConnection);

Is this considered best practice or is this the only practice since there is no native connection pooling or other approaches?

Greenonline
  • 1,330
  • 8
  • 23
  • 31
Amberlamps
  • 39,180
  • 5
  • 43
  • 53

1 Answers1

1

When it comes to how to deal with connections, there are a couple of options:

Single Connection

The simplest option is to just open a single connection and use it through out your app. This is extremely simple but probably doesn't work for larger applications where you might be executing a lot of requests.

In JavaScript, the connection can be appended to the r object and used throughout the application.

import r from 'rethinkdb';
import express from 'express';

let app = express();

r.connect().then((conn) => {
   r.conn = conn;
});

app.use('/table-list', (req, res) => {
  r.db('test').tableList().run(conn)
    .then((result) => {
      return res.json(result);    
    });
});

Open & Close

You can also just open and close a connection every single time you do a request. This approach is also simple, but it's a bit more verbose.

r.connect().then((conn) => 
  return r.db('test').tableList().run(conn)
    .then((result) => {
      console.log(result);    
      return result;
    })
    .then(() => {
      conn.close();
    });
});

Per Request Connection

As you noted earlier, you can also open a connection per-request, use that connection throughout the request, and then close it when the request is done.

Connection Pooling

Finally, you can also use connection pooling if you use rethinkdbdash, which abstracts away connections for you.

Jorge Silva
  • 4,574
  • 1
  • 23
  • 42
  • Personally I do not mind opening and closing on each request. But I am very used to connection pools and I read this is the de facto best practice on how to handle db connections. I am not a Coffeescript expert, but how is the `conn` variable in your single connection example accessible in the use function? – Amberlamps Jul 16 '15 at 19:46
  • It would be attached to the rethinkdb singleton (`r`). That's why, once connected, I do `r.conn = conn`. – Jorge Silva Jul 16 '15 at 22:20
  • You'd need to be careful with this, because you don't want to run any queries before getting the connection. – Jorge Silva Jul 16 '15 at 22:20
  • If you feel you *really* want to have a connection pool, just use rethinkdbdash. :) – Jorge Silva Jul 16 '15 at 22:21
  • But still, you should use `r.conn` in your `run()` function and not `conn` then, right? – Amberlamps Jul 17 '15 at 05:10
  • You should only use the `r.conn` if you only want to have a single connection for your whole app. – Jorge Silva Jul 17 '15 at 16:26