Search code examples
mongodbmicroservices

Database for every microservice


I wonder if few microservices in the same project can share the same database? For example I'm using MongoDB and I'm using few microservices that need a database, should I use one collection for every microservice? Or just create new database for every microservice? Any suggestions?


Solution

  • It is typically recommended to have database per service, however there may be exceptions depending on the specific problem at hand. Your question does not have enough details to provide anything other then general advice.

    The database per service has multiple advantages.

    1. Since each microservice is independently deploy-able. It can change the database schema and not break other services.

    2. There is a clear boundary of ownership of data, no two services write on same data. If there is need for accessing data owned by other services there are patterns(Materialized views, REST endpoints exposing data, Eventual consistency using queues ) to solve that problem.

    3. Depending on the volume of data generated\managed by one microservice the database can be scaled (sharding, read replicas) independently.

    Database per service has significant challenges too (multiple service management overhead, No ACID transaction), it is always recommended to start with a modular monolith and carve out services based on business need.

    References https://learn.microsoft.com/en-us/dotnet/architecture/cloud-native/distributed-data