Roman
Roman

Reputation: 10403

Is it okay to authenticate with MongoDB per request?

I have a Rails controller that needs to write some data to my MongoDB. This is what it looks like at the moment.

  def index
    data = self.getCheckinData

    dbCollection = self.getCheckinsCollection
    dbCollection.insert(data)

    render(:json => data[:_id].to_s())
  end

protected   

  def getCheckinsCollection
    connection = Mongo::Connection.new('192.168.1.2', 27017)
    db = connection['local']
    db.authenticate('arman', 'arman')
    return db['checkins']
  end

Is it okay to authenticate with MongoDB per request?

Upvotes: 1

Views: 359

Answers (3)

Kevin Bedell
Kevin Bedell

Reputation: 13404

In general, this should be avoided.

If you authenticate per request and you get many requests concurrently, you could have a problem where all connections to the database are taken. Moreover, creating and destroying database connections can use up resources within your database server -- it will add a load to the server that you can easily avoid.

Finally, this approach to programming can result in problems when database connections aren't released -- eventually your database server can run out of connections.

Upvotes: 2

d11wtq
d11wtq

Reputation: 35298

It is probably unnecessarily expensive and creating a lot more connections than needed.

Take a look at the documentation:

http://www.mongodb.org/display/DOCS/Rails+3+-+Getting+Started

They connect inside an initializer. It does some connection pooling so that connections are re-used.

Upvotes: 3

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

Is there only one user in the database?

I'd say: don't do the db authentication. If MongoDB server is behind a good firewall, it's pretty secure. And it never ever should be exposed to the internet (unless you know what you're doing).

Also, don't establish a new connection per request. This is expensive. Initialize one on startup and reuse it.

Upvotes: 2

Related Questions