Search code examples
microservices

Using a shared read database in Microservices


It is well known that using a shared database in Microservices is not a good idea, but when we need data in another Microservice we should use messaging brokers like RabbitMQ. If the data is required just to build a new materialized view, wouldn´t be easier if some kind of shared read database was available? Or should we read 'you shall not share databases across Microservices' as do not share a writeable nor a readable database?


Solution

  • In Microservices there isn't right or wrong but best practices. The purpose of microservices is they can operate and work independently. Keeping this in mind Read Replicas are fine as long as they are operating independently and are used only to create materialized view. If primary DB goes down , your read replicas should keep on operating. Technically they both are separate/independent databases for different purposes.

    When using this approach you need to be aware of consistency. This kind of setup will be eventually consistent , so if your primary is updated it will take sometime to get reflected in read replicas and you may get stale copy while data is being replicated. If you are after strong consistency this may not be good strategy.

    based on comments below

    Materialized view and read replicas are two different things. You would only use Read replica to create Materialized view. But you don't do anything within the replica itself. You need to create the Materialized view into cache , separate DB or even NoSQL db. We use read replicas Only to off load the query load from write database. Materialized views are disposable. You can simply dispose them and recreate using Read Replicas. In this kind of approach you could have a periodic job that will be recreating the materialized view based on interval you choose. If you have heavy write load database it's always a good idea to create read replicas to create Materialized views. There is not other purpose of read replicas in this context. You can even use read replicas to create views on the fly , but they are simple views and you will be querying the data on the fly and may not be as fast as materialized view.

    The second approach like you said is to listen to events. They are simple in a way that as soon as you would listen to the events you can update your materialized view. But again they are disposable and you can always query your actual/master database to recreate/update materialized view.