Multi-Tenant Data Isolation in a Microservices Architecture
Technical implementation of SaaS multi-tenant data isolation in a SpringCloudAlibaba microservices architecture: database schema isolation, cache key isolation, and message queue topic isolation.
One of the core challenges of a SaaS platform is multi-tenant data isolation. ZhiShuYun needed to ensure complete data invisibility between tenants while maximizing resource utilization. This article shares our multi-tenant isolation practices under the SpringCloudAlibaba microservices architecture.
Database-level isolation uses a schema-per-tenant approach. Each tenant has an independent schema in MySQL, with a MyBatis interceptor dynamically switching data sources before SQL execution. Compared to the Shared Database approach, schema isolation achieves the optimal balance between security and resource elasticity: tenant data is physically isolated while sharing the database instance's compute and storage resources.
Cache isolation is an easily overlooked aspect. We use a key prefix approach in Redis: all cache keys are prefixed with the tenant ID (e.g., {tenantId}:product:list), with a customized Spring Cache KeyGenerator automatically injecting tenant information. At the message queue level, RocketMQ uses topic isolation, with each tenant having an independent message topic (e.g., order-{tenantId}), ensuring complete message isolation between tenants.
At the gateway layer, we extract the tenantId from the JWT token through a Spring Cloud Gateway GlobalFilter and write it to the ThreadLocal context. All subsequent service calls automatically propagate the tenantId via a Feign interceptor, eliminating the need for explicit passing in business code. Tenant-level rate limiting and circuit breaker policies are also implemented to prevent a single tenant's abnormal traffic from affecting others.