DEV Community

Cover image for When you need Database per Service ?
Danyson
Danyson

Posted on • Updated on

When you need Database per Service ?

Imagine opening a food ordering app.
                ||
                \/
       Selecting Dosai to eat.
                ||
                \/
       Three services spawns 
       //        ||        \\
      \/         \/         \/
   Ordering   Preparing   Delivery
Enter fullscreen mode Exit fullscreen mode

In a regular monolithic architecture three of these services share a single Food database.

Once the we select the food it arrives to Ordering service which intimates the hotel and updates the Food DB's Order table or collection.

Next( ), Food is been prepared at Preparing service (cooking & packaging) and updates the Food DB's Prepare table or collection.

Next( ), Food is been Delivered by Delivery service and updates the Food DB's Delivery table or collection.

But a delivery app is not that simple to serve few hotels.

Thousands of hotels will be there.

Ordering has varities of style.

Preparing has lots of sub process in itself.

Delivery has lots of modes with communicating different people.

Putting all these data in to single DB with several tables or collections, managing huge amount of data on these several tables and collections is sort of a pain when you want to scale and manage the service with less complexity.

The main Complexity arises to whoever developes these services in the backend, also when finding bugs and fixing issues.

How about each service has its own database ?

  1. Ordering service has its own Order DB.
  2. Preparing service has its own Prepare DB.
  3. Delivery service has its own Delivery DB.

Lets wrap them up in a container.

After wrapping OrderDB with Docker --> connect to

--> OrderingService

After wrapping PrepareDB with Docker --> connect to

--> PreparingService

After wrapping DeliveryDB with Docker --> connect to

--> DeliveryService

Ok wait, now how do you synchronize these services ?

The flow of process is not asynchronous.

They need to be synchronized like,

 Order
  ||
  \/
Prepare
  ||
  \/
Deliver
Enter fullscreen mode Exit fullscreen mode

Somebody has to tell Preparing Service about the arrived Order.

Next( )

Somebody has to tell Delivery service about the food been prepared.

For this we need Redis PUB/SUB to build a message broker between our OrderDB --> PrepareDB --> DeliveryDB.

Order arrives, Ordering Service places order and updates OrderDB and says to the Preparing Service about the arrived order.

After hearing about the Order, Preparing service prepares food and updates the PrepareDB and says to the Delivery Service about the Prepared food.

After hearing about the prepared food, Delivery Service delivers food and updates DeliveryDB.

Now thats how Database per service will be utilized.

Discussion (0)