r/SpringBoot • u/bibb_ekkkk • 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
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.
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