Partitioning and sharding in system design: choosing a shard key from access patterns, hash vs range vs directory sharding, hot keys, resharding with consistent hashing or a shard map, cross-shard queries, and Azure SQL vs Cosmos DB.
Partitioning splits data into pieces; sharding puts those pieces on separate servers so writes scale out. I shard last, after caching, replicas and a bigger tier, because it's hard to undo. The shard key comes from the dominant access pattern: high cardinality, even load, and most queries served by one shard — in SaaS that's usually TenantId. Hash sharding spreads load evenly but loses range scans; range keeps scans but creates hot ranges; a shard map (directory) lets me move big tenants on their own. Hot keys get split, salted or isolated. I plan resharding from day one with many virtual partitions mapped to fewer nodes. Cross-shard queries go to a read model or search index, never a distributed transaction. The trade-off: linear write scale in exchange for losing joins, global constraints and simple operations.
"First I'd separate the words. Partitioning is splitting data into pieces; sharding is putting those pieces on different machines so the write load scales out. SQL Server table partitioning is partitioning on one server — useful for maintenance and archiving, but it doesn't add write capacity. Sharding does, and I treat it as a one-way door: once data is spread out, joins, unique constraints, transactions and reporting all get harder. So I only shard when caching, read replicas and a bigger tier have run out.
The decision that matters is the shard key. I pick it from the access pattern, not the schema: high cardinality, load that spreads evenly, and — most importantly — most requests touch exactly one shard. For a SaaS product that's usually
TenantId. For example, at [company] we [had a multi-tenant SQL database at around 2 TB where three tenants caused 40% of the load]. We moved to a shard map with database-per-tenant for the large ones and pooled databases for the small ones, [and p99 for the small tenants dropped from 1.2 s to 180 ms] because the noisy ones were isolated. Hash sharding gives even spread but no range scans; range sharding keeps scans but makes hot ranges; a directory gives flexibility at the cost of a lookup and a cache. Hot keys get special treatment: a big tenant gets its own shard, a hot counter gets salted, and in Cosmos DB a hierarchical partition key lets one tenant span more than one 20 GB logical partition.The mistake I see is not planning for resharding. If you do
hash(key) % 4and later need 5 shards, almost every key moves. I use many virtual partitions — say 1,024 — mapped to a few physical databases, so growing means moving whole partitions. And cross-shard queries go to a separate read model or a search index, fed by events. A senior shards along the line the business already draws, and keeps everything that crosses that line asynchronous."
| Strategy | How it routes | Good at | Bad at |
|---|---|---|---|
| Hash | hash(key) → partition |
Even spread, no hot ranges | Range queries, moving one tenant |
| Range | Key ranges (A–F, dates) | Range scans, time-based archiving | Hot ranges (today, new IDs) |
| Directory / shard map | Lookup table key → shard | Moving tenants, mixed isolation | Extra lookup, map must be cached and highly available |
| Geo | Region of the user | Data residency (Australia), latency | Users who travel, global queries |
| Candidate | Cardinality | Even load? | Single-shard queries? | Verdict |
|---|---|---|---|---|
TenantId |
Thousands | Skewed by big tenants | Yes, almost all | Good with a shard map for big tenants |
OrderId |
Huge | Yes | Only by-id lookups; 'my orders' fans out | Poor for user-centric reads |
CustomerId |
Huge | Mostly | Yes for customer screens | Good for B2C |
CreatedDate |
Low per day | No, today is hot | Range reports only | Bad as a primary key for writes |
| Need | Azure | AWS note |
|---|---|---|
| Relational, per-tenant | Azure SQL database-per-tenant in elastic pools + shard map | RDS / Aurora per tenant |
| Relational, very large single DB | Azure SQL Hyperscale (storage and read scale, single writer) | Aurora |
| Automatic partitioning | Cosmos DB (partition key; 20 GB / 10,000 RU/s per logical partition as of November 2026) | DynamoDB |
| Distributed Postgres | Azure Cosmos DB for PostgreSQL (Citus) | Aurora Limitless |
A [rostering] SaaS sharded by tenant into [40] Azure SQL databases in two elastic pools, with the top [5] tenants on dedicated databases. Write throughput grew [6×] with no single database above 55% CPU, and cross-tenant reporting moved to a nightly feed into [Fabric / Synapse], removing all cross-shard queries from the API.
Checks whether the candidate can choose a shard key from access patterns and handle the hard parts (hot keys, resharding, cross-shard operations) rather than just saying "we'll shard it".
Green flags
Red flags
hash % N with no plan to change NA single primary has one transaction log and one set of locks. Vertical scaling raises the ceiling but not forever, and costs grow faster than linear. Sharding gives each shard its own log, buffer pool and locks:
[router / shard map]
/ | \
[shard 0] [shard 1] [shard 2]
tenants A-x tenants y-z big tenant Q
Naive modulo:
shard = hash(key) % N
N: 4 -> 5 => ~80% of keys change shard
Consistent hashing places nodes and keys on a ring; adding a node moves only ~1/N of keys. Virtual partitions are the practical version: hash into a fixed, large number of slots (e.g. 1,024, or Redis Cluster's 16,384) and map slots to physical nodes. Resharding = moving slots. Cosmos DB does the same internally: logical partitions are hashed into ranges owned by physical partitions, which split automatically when they exceed their storage or throughput limit.
The Azure SQL Elastic Database tools implement steps like these with the split-merge service and ShardMapManager, and the client library performs data-dependent routing with OpenConnectionForKey.
key#0..key#15, read all 16 and merge (counters, likes)./tenantId/userId lets a tenant exceed 20 GB because the second level spreads it over physical partitions.| Need | Approach |
|---|---|
| Query across tenants | Scatter-gather with a timeout and partial results, or a read model (Azure AI Search, a reporting warehouse) fed by change feed / CDC |
| Global unique constraint (email) | A separate small global table or a lookup service |
| Transaction across shards | Avoid; use a saga or outbox with idempotent steps |
| IDs | Generate without coordination (UUIDv7, Snowflake-style) |
N shards = N times schema migrations, backups, monitoring and failovers. Use automation (deploy migrations per shard with a job, e.g. elastic jobs) and keep the shard count small with virtual partitions.
% 4 and % 5 and count how many move; then repeat with 1,024 virtual slots.SELECT TenantId, COUNT(*) ... GROUP BY TenantId ORDER BY 2 DESC and compute what share the top 1% holds./country) in the emulator, load data and inspect partition key ranges and 429 rates.Task.WhenAll and a 2 s timeout that returns partial results.Data-dependent routing with a small cached shard map (directory sharding). Large tenants can be moved by changing one row.
namespace Saas.Sharding;
using System.Collections.Frozen;
using System.IO.Hashing;
using System.Text;
using Microsoft.Data.SqlClient;
public sealed record ShardMap(FrozenDictionary<int, string> SlotToConnection,
FrozenDictionary<Guid, string> PinnedTenants);
public interface IShardMapProvider
{
ValueTask<ShardMap> GetAsync(CancellationToken ct); // cached; refreshed on change
}
public sealed class ShardRouter(IShardMapProvider maps)
{
private const int Slots = 1024; // virtual partitions: resharding moves slots, not rows one by one
public async ValueTask<SqlConnection> OpenForTenantAsync(Guid tenantId, CancellationToken ct)
{
var map = await maps.GetAsync(ct);
// Whales are pinned to dedicated databases by the directory.
var cs = map.PinnedTenants.TryGetValue(tenantId, out var pinned)
? pinned
: map.SlotToConnection[Slot(tenantId)];
var conn = new SqlConnection(cs);
await conn.OpenAsync(ct);
return conn;
}
// Stable hash: string.GetHashCode is randomised per process and must never be used for routing.
private static int Slot(Guid tenantId) =>
(int)(XxHash32.HashToUInt32(tenantId.ToByteArray()) % Slots);
}
Cosmos DB hierarchical partition key so one large tenant can grow past the 20 GB logical partition limit:
namespace Saas.Sharding;
using Microsoft.Azure.Cosmos;
public static class Containers
{
public static Task<ContainerResponse> CreateOrdersAsync(Database db, CancellationToken ct) =>
db.CreateContainerIfNotExistsAsync(
new ContainerProperties("orders", partitionKeyPaths: ["/tenantId", "/customerId"]),
ThroughputProperties.CreateAutoscaleThroughput(10_000),
cancellationToken: ct);
}
hash % N with physical nodes. Why it is wrong: Changing N moves most keys. Instead: Use consistent hashing or a fixed number of virtual partitions mapped to nodes.string.GetHashCode() for routing. Why it is wrong: It is randomised per process in .NET, so instances disagree. Instead: Use a stable hash such as XxHash or a lookup.Sharding is a business decision disguised as a technical one: the shard key should match a boundary the business already has (tenant, region, customer), because every feature that crosses it becomes asynchronous. A senior also prices the operational cost — N times the migrations, backups and alerts — and designs for the move of one tenant, which is the operation you will actually do most. Each shard can still have its own read replicas for read-write splitting, and per-shard dashboards are what tell you when to move a tenant before customers notice.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| Read replicas (read-write splitting) | Reads dominate, writes still fit one primary | Replica lag, routing | Write-bound systems |
| Hyperscale / bigger tier | Up to ~100 TB storage, writes still fit one node | Money, one writer | Write rate exceeds one log |
| Database-per-tenant + pools | B2B SaaS, isolation and residency matter | Many DBs to operate | Millions of tiny tenants |
| Hash-sharded shared schema | B2C, huge numbers of users | Cross-user features async | Strong need to move single tenants |
| Cosmos DB partitioning | Key-value or document access by a clear key | RU cost, query limits | Heavy ad-hoc relational reporting |
I start with numbers: data size and growth, hot versus cold data, read/write ratio and tenant distribution. Then:
SWITCH makes archiving and purging metadata-only and enables partition-level index rebuilds. It is not an automatic speed-up and needs queries that allow partition elimination.Shard only when scale-up, read scale-out and archiving are exhausted: it moves complexity into the application.
A distributed cache is partitioned in-memory storage. Keys map to hash slots (Redis Cluster uses 16,384), and slots map to shards, so adding a node moves only the slots it takes over; consistent hashing with virtual nodes achieves the same thing. Each shard has a primary and asynchronous replicas; on failure a replica is promoted, accepting the loss of a few recent writes, which is fine for a cache. Memory is bounded by TTLs and approximate LRU/LFU eviction. Smart clients keep the slot map and follow redirects. Hot keys need a local L1 cache or key replication, and stampedes need request coalescing. Then the honest answer: I'd buy Azure Managed Redis and build only the .NET client layer: HybridCache, key design, invalidation and observability. The trade-off: building teaches the internals but gives you a tier-one system to run forever.
A consistency model is the contract that says which values a read may return when data is replicated. At one end, strong (linearisable) consistency makes every read see the latest committed write, as if there were one copy. At the other, eventual consistency only promises replicas converge once writes stop. In between are the session guarantees: read-your-writes (you see your own updates), monotonic reads (you never go back in time) and consistent prefix (you never see writes out of order). Cosmos DB exposes this as five levels: Strong, Bounded Staleness, Session (the default), Consistent Prefix and Eventual; stronger levels cost more latency and request units, and Strong can't be used with multi-region writes. I choose per feature: what does a stale or out-of-order read cost here? The trade-off is freshness against latency, cost and availability.
How to tell it (STAR)
**S:** Our [practice-management] SaaS ran all [1,800] tenants in one database, and [3] of them caused [40%] of the load. **T:** I had to stop the big tenants hurting the small ones without a rewrite. **A:** I showed that almost every query was single-tenant, chose TenantId as the shard key with a shard map, moved the whales to dedicated databases one at a time with a short cut-over, and spread the rest across pooled databases. **R:** Small-tenant p99 dropped from [1.2 s] to [180 ms], and we had room for [3×] growth.
Last updated 23 Nov 2026.