Production-ready multi-tenant database sharding solution with Spring Boot auto-configuration.
sharding-springboot/
βββ sharding-springboot-starter/ # Core sharding library
βββ sample-sharded-app/ # Demo ticket management application
βββ docs/ # Comprehensive documentation
β
Directory-Based Sharding - Tenant-to-shard mapping via tenant_shard_mapping table
β
Multi-Replica Support - Master-replica configuration with automatic read/write splitting
β
Auto-Configuration - Zero-config Spring Boot integration
β
Entity Validation - @ShardedEntity annotation validation during startup
β
Query Validation - SQL-level tenant filtering with configurable strictness
β
Connection Routing - Intelligent routing based on tenant context
β
HikariCP Optimization - Database-specific tuning with optimal defaults
β
Batch Processing - Tenant iterator for background jobs
β
Monitoring - JMX metrics and routing statistics
β
Multi-Database Support - Native MySQL and PostgreSQL support with database-specific optimizations
β
Dual DataSource Configuration - Automatic separation of global and sharded entities with package-based routing
ShardingConfigProperties- Main configuration with flat structureHikariConfigProperties- Comprehensive HikariCP settingsShardingAutoConfiguration- Spring Boot auto-configurationShardingDataSourceAutoConfiguration- Dual DataSource auto-configuration with Lombok-based propertiesDualDataSourceProperties- Package-based routing configuration (Lombok)HikariConfigUtil- Optimal defaults and database-specific optimizations
TenantContext- Thread-local tenant informationTenantInfo- Immutable tenant data holder
TenantShardMappingRepository- Directory-based tenant-shard mappingTenantShardMapping- Data model for lookup tableShardUtils- Comprehensive shard management utilitiesDatabaseSqlProvider- Interface for database-specific SQL operationsMySQLSqlProvider- MySQL-specific SQL implementationPostgreSQLSqlProvider- PostgreSQL-specific SQL implementationDatabaseSqlProviderFactory- Automatic database detection and provider selection
ShardAwareDataSourceDelegate- Routes connections based on tenant contextRoutingDataSource- Spring DataSource integrationRoutingDataSource- Enhanced routing DataSource with dual configuration supportShardDataSources- Master-replica container with load balancing
QueryValidator- SQL query validation for tenant filteringEntityValidator-@ShardedEntityannotation validationValidatingDataSource- DataSource proxy for query interception
TenantIterator- Batch processing with parallel support- Background job utilities for cross-tenant operations
@ShardedEntity- Marker for sharded entities
PostgreSQL Configuration (Default):
# Global Database
app.sharding.global-db.url=jdbc:postgresql://localhost:5432/global_db
app.sharding.global-db.username=global_user
app.sharding.global-db.password=global_password
# Shard Configuration
app.sharding.shards.shard1.master.url=jdbc:postgresql://localhost:5432/shard1_db
app.sharding.shards.shard1.replicas.replica1.url=jdbc:postgresql://localhost:5433/shard1_db
app.sharding.shards.shard1.hikari.maximum-pool-size=20
app.sharding.shards.shard1.latest=true
# Validation
app.sharding.validation.strictness=STRICT
app.sharding.tenant-column-names=tenant_id,company_idAlternative Database Support:
- Full MySQL 5.7+ support with optimizations
- Full PostgreSQL 11+ support with optimizations
- Automatic database type detection from JDBC URLs
Add the sharding starter to your project's pom.xml:
<dependency>
<groupId>com.valarpirai</groupId>
<artifactId>sharding-springboot-starter</artifactId>
<version>1.0.0</version>
</dependency>@Entity
@ShardedEntity // Routes to tenant-specific shard
public class Customer {
@Column(name = "tenant_id", nullable = false)
private Long tenantId;
// ... other fields
}
@Service
public class CustomerService {
public Customer save(Customer customer) {
return TenantContext.executeInTenantContext(customer.getTenantId(), () -> {
return customerRepository.save(customer);
});
}
}Location: sample-sharded-app/
Purpose: Complete demonstration of the sharding library
- Sharded entities (
Customer) with tenant isolation - Non-sharded entities (
GlobalConfig) in global database - REST API with tenant context management
- Database setup scripts with sample data
- Configuration examples
POST /api/customers/set-tenant/{tenantId} # Set tenant context
POST /api/customers # Create customer
GET /api/customers # Get customers for tenant
GET /api/customers/{id} # Get specific customer
PUT /api/customers/{id} # Update customer
DELETE /api/customers/{id} # Delete customer
- STRICT: Throw exception if tenant_id missing (Production)
- WARN: Log warning but proceed (Development)
- LOG: Info logging only (Testing)
- DISABLED: No validation (Not recommended)
- β MySQL 5.7+ - Full support with MySQL-specific optimizations
- β PostgreSQL 11+ - Full support with PostgreSQL-specific optimizations
- π SQL Server - Planned for future release
- π Oracle - Planned for future release
- MySQL: Prepared statement caching, server-side preparation, UTF8MB4 charset support
- PostgreSQL: Statement cache optimization, prepared statement thresholds, cache size tuning
- SQL Server: Statement pooling configuration (planned)
- Oracle: Implicit statement caching (planned)
The library automatically detects the database type from JDBC URLs and applies appropriate SQL syntax and optimizations:
- MySQL: Uses
DATABASE()function and MySQL-specific table creation syntax - PostgreSQL: Uses
current_schema()function and PostgreSQL-specific syntax - Fallback: Defaults to MySQL provider if detection fails
maximum-pool-size: 20 (balanced for production)minimum-idle: 5 (maintain ready connections)connection-timeout: 30s (standard timeout)idle-timeout: 10m (cleanup idle connections)max-lifetime: 30m (connection refresh)
- ROUND_ROBIN: Distribute load across replicas
- RANDOM: Random replica selection
- FIRST_AVAILABLE: Always use first replica
# 1. Build the library
mvn clean install
# 2. Set up PostgreSQL databases
cd sample-sharded-app
psql -U postgres -f database-setup.sql
# 3. Run the sample application
mvn spring-boot:run
# 4. Access Swagger UI
open http://localhost:8080/swagger-ui.htmlπ Complete Documentation - Comprehensive guides, deployment, testing, and reference
- Getting Started - Installation and basic usage
- Migrations Guide - Database schema changes across shards
- Transactions Guide - Transaction patterns
- Zero Downtime Deployment - Production best practices
- Integration Tests - Testing guide (69 comprehensive tests)
- Technical Specification - Complete library reference
<dependency>
<groupId>com.valarpirai</groupId>
<artifactId>sharding-springboot-starter</artifactId>
<version>1.0.0</version>
</dependency># Global Database
app.sharding.global-db.url=jdbc:postgresql://localhost:5432/global_db
app.sharding.global-db.username=user
app.sharding.global-db.password=pass
# Shard
app.sharding.shards.shard1.master.url=jdbc:postgresql://localhost:5432/shard1_db
app.sharding.shards.shard1.master.username=user
app.sharding.shards.shard1.master.password=pass
app.sharding.shards.shard1.latest=true@Entity
@ShardedEntity
public class Customer {
@Column(nullable = false)
private Long tenantId; // Required
private String name;
}@Service
public class CustomerService {
public Customer save(Long tenantId, Customer customer) {
return TenantContext.executeInTenantContext(tenantId, () -> {
return customerRepository.save(customer);
});
}
}- Global DB: Central database for tenant-shard mappings and global entities
- Shard DBs: Multiple databases with tenant-specific data (master + replicas)
- Global entities/repos β
*.entity.global,*.repository.global - Sharded entities/repos β
*.entity.sharded,*.repository.sharded
- SEQUENTIAL: One shard at a time (safest)
- PARALLEL: All shards simultaneously (fastest)
- WAVE: Batches with delays (recommended for production)
- CANARY: Test on one shard first (critical changes)
For Developers:
- β Zero-configuration Spring Boot integration
- β Type-safe entity validation at compile time
- β Database-agnostic (PostgreSQL, MySQL with auto-detection)
- β Comprehensive testing suite (69 integration tests)
For Operations:
- β Multiple migration strategies (sequential, parallel, wave, canary)
- β Database-specific HikariCP optimizations
- β JMX metrics and health endpoints
- β Read-write splitting with replica support
For Business:
- β Complete tenant data isolation
- β Horizontal scalability (add shards as needed)
- β Production-ready with zero-downtime deployment patterns
- β Compliance-friendly with strict query validation
The sample-sharded-app demonstrates a multi-tenant ticket management system:
- Account signup with automatic demo environment setup
- JWT authentication with tenant validation
- User and ticket management with role-based permissions
- Liquibase migrations across global DB and shards
- Comprehensive tests including API, security, and migration tests
API Documentation: http://localhost:8080/swagger-ui.html (when running)
- Java 21
- Spring Boot 3.4.5
- Hibernate/JPA
- HikariCP (connection pooling)
- Liquibase (schema migrations)
- PostgreSQL / MySQL (auto-detected)
- TestContainers (integration tests)
Licensed under the MIT License. See LICENSE file for details.
For complete documentation, see docs/ directory.