spring-projects / spring-modulith

Modular applications with Spring Boot
https://spring.io/projects/spring-modulith
Apache License 2.0
774 stars 124 forks source link

Insolated datasources per module #250

Open victorherraiz opened 1 year ago

victorherraiz commented 1 year ago

is there any way to create a diferent datasource per module (e.g. diferent driver, server, db...) and insolate that resources to avoid access from different modules.

I could be very nice feature to prevent data coupling and prepare the module to be use as an independant micro-service if is necesary.

eynoc-coder commented 1 year ago

I recommend creating a Config class within an internal package for each module and using Spring configuration to set up a dedicated datasource for each module. This https://www.baeldung.com/spring-data-jpa-multiple-databases provides an example of how to do this. Additionally, you can write an ArchUnit rule to prevent each datasource from scanning entities outside of their respective modules.

It still an Springboot application so all the features present in the previous versions still there. You just have to adapt it using the modulith rules.

I guess that respond your question.

odrotbohm commented 1 year ago

Yeah, I guess using an AbstractRoutingDataSource with a key per module registered via an interceptor, decorating entries into the module should do the trick. I wonder if there's any more direct support you imagine from Spring Modulith, because unless I overlook anything, it all boils down to your persistence setup.

victorherraiz commented 1 year ago

@odrotbohm, nice idea. I was not aware of AbstractRoutingDataSource solution. Is there any context holder that contains information of the current module to implement AbstractRoutingDataSource? With that, implementing an AbstractRoutingDataSource should be easy.

Maybe a future datasource per module configuration could be a great option.

cassis163 commented 11 months ago

@odrotbohm It would be neat to add an example where modules use the database per module pattern, since using a modular monolithic architecture does not imply a specific way to do persistence (e.g. shared database pattern). Also, this is not something that is currently mentioned in the documentation. The docs do not mention different ways to do persistence.

One thing to note is that using the database per module pattern introduces new challenges. One of these is that this pattern often comes with data duplication across databases for various use-cases. For example, you cannot do efficient cross-database queries, so oftentimes data duplication through messaging offers the ability to query while maintaining low-coupling.

I should add that I merely skimmed through the documentation, so I potentially failed to read about persistence strategies.

kriehzoo commented 10 months ago

Same thought here and it would be great to have an example for this :-)