Video in progress
The data now has to be split across several shards. What breaks in a service built with Hibernate, and how do you approach it?
Hibernate assumes one logical database: joins, transactions, sequences and polymorphic queries do not work across shards. I tie the shard key to the aggregate ID and design so that every transaction stays inside one shard; routing happens at the DataSource level.
📖 Answer
The Hibernate Shards project was abandoned long ago, so today sharding is done below Hibernate or outside it.
Options:
- routing at the application level:
AbstractRoutingDataSource+ a separate pool per shard, taking the shard key from the request context; - at the proxy level: Vitess (MySQL), Citus (PostgreSQL). The application sees one database and the split happens in the proxy;
- a separate
EntityManagerFactoryper shard: a lot of memory and startup time, rarely needed.
What breaks:
- there are no joins or foreign keys across shards. If
Orderis on shard 3 andCustomeris on shard 7,@ManyToOnedoes not work; - a transaction is limited to one shard; writing to two shards needs a saga or an outbox;
- IDs have to be globally unique: sequences are separate per shard, so use UUIDv7 or Snowflake-style IDs;
- "a report across all orders" needs scatter-gather or a separate analytics store;
- the L2 cache key has to take the shard into account.
So first I revisit the domain: the shard key is chosen so that one aggregate and all its associations live on one shard (for example tenant_id or customer_id). Then 90% of the service code stays unchanged: at the start of the transaction you determine the key and pick the right DataSource.
And I ask the question: do we really need sharding? Often vertical scaling, read replicas, partitioning and archiving old data last several years, and they are far cheaper than sharding.
Sign up to mark studied questions and save your progress.