Microservices with the same database

microservicesrelational-database

I have a monolith application on a server and I want to break it into multiple microservices.

Because of that for the moment I have to use the same database for all the microservices and each microservice accessing only his own tables.

So my question is how can I reuse the database connection among microservices and still keep the independently of one another because at some point in the future I may want for some of them to use another database .

I ask this question because I think is an overhead to make a new database connection for each microservice if they all use the same database because a single page logic can use more then 10-20 microservices .

Best Answer

The fact that those different processes use separate connections is (mostly) irrelevant.

The usual concern is that opening and closing a connection is expensive in terms of time and CPU resources. With many databases, this concern is invalid because of connection pooling: there is an overhead the first time you connect to the database, but the next time you need to do a query within the same process, an existent connection is reused under the hood, even if in code, you explicitly closed the connection.

What will happen in your case is that you'll pay the cost of opening twenty connections the first time when twenty microservices start after, for instance, the server reboots. Once this is done, each service will reuse connections already opened before.

What would be a problem is if you have a lot of microservices accessing the database, or if the database, for a given reason, cannot accept too many connections. Since you are talking about twenty microservices, I won't be concerned; for instance, “SQL Server allows a maximum of 32,767 user connections.” (source) If you use a more exotic database or a database which has an exotic configuration or if each service needs, for some reason, to open many connections at once, this could indeed become an issue.

Related Topic