Hands-On Microservices with Kubernetes
上QQ阅读APP看书,第一时间看更新

One data store per microservice

The one data store per microservice is a crucial element of the microservice architecture. The moment two microservices can access directly the same data store, they are tightly coupled and are no longer independent. There are a few important nuances to understand. It may be OK for multiple microservices to use the same database instance, but they must not share the same logical database.

The database instance is a resource provisioning concern. In some cases, the team developing the microservice is responsible for provisioning its data stores too. In this case, the wise move may be to have physically separate DB instances for each microservice and not just logical ones. Note that when using cloud data stores, the microservice developer is not in control and unaware of the physical configuration of the data store.

We agree that two microservices shouldn't share the same data store. But, what about a single microservice managing two or more data stores? This is generally also frowned upon. If your design calls for two separate data stores, it's better to dedicate a microservice to each one:

There is one common exception—you may want to manage an in-memory data store (cache) and a persistent data store by the same microservice. The workflow is that the service is writing to the persistent store and the cache and serving queries from the cache. The cache is either refreshed periodically, or based on change notification, or when there is a cache miss.

But, even in this case, it may be a better design to have a separate centralized cache, such as Redis managed by a separate microservice. Remember that each microservice may have multiple instances in a large system that serves many users.

Another reason to abstract away the physical configuration and provisioning of data stores from the microservices themselves is that those configurations may be different in different environments. Your production environment may have physically separate data stores for each microservice, but, in your development environment, it may be better to have just one physical database instance with lots of small logical databases.