Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it expensive to keep database connections open?

I was in a meeting with a few software developers, and was recommended to close database connections as soon as possible in my application code? Can somebody please tell me what is the harm of keeping a connection open in an application.

I was reading the data from a single table of a database

like image 660
TimeToCodeTheRoad Avatar asked Jul 25 '12 21:07

TimeToCodeTheRoad


People also ask

Should you keep database connection open?

For fast response time and high throughput, it's actually best to keep database connections open and reuse them for subsequent requests. Most database frameworks offer some kind of connection pool mechanism where a request handler can get a database connection for its work and return it to the pool afterwards.

Why database connection is expensive?

And, the reason it's expensive is, clients connect to the database with a regular TCP connection which requires the three-way handshake to establish a new connection. On top of that, each connection need to be authenticated and authorized, adding to the delay.

What happens if you don't close database?

It will stay open in memory, clogging that address until the system times it out and closes it. There was a time that this was a real problem even on small websites. People would open a connection, and it would stay open for weeks. As more users hit that same page, more and more connections would open.


1 Answers

Think of it like seats on a bus.

As you open connections, you fill up those seats - eventually, the bus is full and can no longer accept passengers (or open more database connections). Any time the bus has to refuse a passenger because it's at capacity, that passenger has to wait for another bus to come by.

By closing your connections when you're done with them, you free up room for more connections - which means more programs that need to interact with the database can do what they need to, without having to wait around for connections to free up. Not closing your connections means the database needs to figure out what to do with all the connections sitting around, which can cause problems if your database isn't closing connections as quickly as you're opening new ones.

This changes when you're using a connection pool (see comments below); in those situations you'll want your pool to handle opening and closing connections for you. If you're not pooling your connections, keeping them open any longer than you need to is wasting resources.

like image 65
girasquid Avatar answered Nov 16 '22 01:11

girasquid