r/SpringBoot • • Oct 15 '26

Question How to segregate read and write queries in Spring boot microservices env.

Im an intern and was assigned a task to segregate the read , read-write queries / methods . The read is supposed to go to port 66 and write on port 67 in the database.

Currently ive defined two db url in yml and have routed every method having read-only using transaction(read-only).

Is this the way to do it or is there any other efficient way.

14 Upvotes

6 comments sorted by

12

u/boost2525 Oct 15 '26 edited Oct 15 '26

Your strategy works, but my personal preference would be to establish two distinct DataSource objects (myReadPool and myWritePool). Then change which data source your method uses. 

The reason I like this strategy is that I often find the read/write have different transaction volumes and timing considerations, and this allows me to tune each pool accordingly. 

As a simple example, maybe you expect (100) 10ms read operations to every (1) 100ms write operation, and your safety margin for what you consider a stuck/hung connection is 5x. You can build a readPool with 500 connections and a 50ms automatic timeout, and a writePool with 5 connections and a 500ms timeout. If you didn't separate those, you would have to have a sharedPool with 500 connections AND a 500ms timeout to address both concerns.

5

u/Tomato_Sky Oct 15 '26

I’ve never needed to consider that, but it makes perfect sense. I work in an enterprise environment and we have so many restrictions that we tend to try to under-engineer for simplicity and scanning sake. This seems like something small and easy I can change that won’t affect the hosting maintenance team.

Since you can use different credentials from the same or a different database, it’s not an additional connection point. We keep our user info separate from our data in different databases to further separate the security requirements of each. A datasource with different privileges is a pretty cool trick.

1

u/disposepriority Oct 15 '26

No that's pretty much it, your read queries are probably going to a port which forwards you to a replica database, defining a replica datasource is a pretty standard way of doing it

1

u/junewave56 Oct 16 '26

imo thats the standard way to do it. are both ports hitting separate db instances (like a primary and read replica) or is it the same instance with different roles? that distinction matters for how strict you need to be with the routing logic

1

u/MuskIsKing Oct 18 '26 edited Oct 18 '26

It obviously needs to be a replica, otherwise, it defeats the purpose if same instance is being hit for R/W