Group users by a sharding key that matches your dominant access pattern, usually a hashed user ID for even spread or a tenant/account ID when data is naturally partitioned by customer. Then add a separate mechanism, such as a directory table or range-based routing layer, for any secondary grouping like region or plan tier. The grouping that decides where a row lives must be stable, high-cardinality, and present in nearly every query; everything else is metadata you can move later.
That single rule covers most of the design. The hard part is not picking a key but deciding which of several plausible groupings actually governs physical placement, and what happens when a user's attributes change. A user who upgrades plans, moves country, or joins an enterprise account should not trigger a cross-shard migration if you grouped on the wrong field. Getting this right requires separating placement groupings from policy groupings before you write a single shard map.
This article walks through the decisions in the order you'd make them: identifying access patterns, choosing a key, handling users with multiple grouping attributes, sizing shards, routing requests, and surviving rebalances.
Start from query patterns, not from user attributes
The most common failure in scaling a database is choosing a grouping that looks natural on an entity diagram rather than in production queries. User tables tempt you to group by country, signup cohort, or plan because those are columns you already have. But placement should follow the access path that carries the most load and needs the tightest consistency.
Write down the top five to ten queries by volume and by latency sensitivity. Typical candidates for a user-centric system look like this:
Fetch a user's profile by user ID. List a user's orders or messages, filtered by that user. Load a session or authentication record by user ID or token. Aggregate activity for a tenant or organization. Fetch a batch of users for an admin operation, filtered by region or status. Run analytics over large user populations by date range.
For each query, note the filter columns and whether it touches one user, a small set, or a broad scan. The grouping key should be a column that appears in the highest-load, most latency-sensitive, single-user or single-tenant paths. If 90% of your traffic is "get everything for this user," then user ID is the placement key almost by default. If your product is business-to-business and most queries are scoped to an organization, the organization ID wins, because grouping by individual user would scatter one tenant's data across every shard and turn a single dashboard load into a fan-out across dozens of nodes.
A practical test: for each candidate key, ask how many shards a typical request would touch. One is ideal. A handful is acceptable for read-heavy aggregation. Dozens or hundreds means you've grouped on the wrong thing, and you'll pay for it on every request rather than once at write time.
Separate placement grouping from policy grouping
The confusion that derails scaling projects is treating "grouping users" as one decision. It's at least two.
Placement grouping determines which physical shard, partition, or node stores a row. It must be immutable in practice or changeable only through an explicit, rare migration. If a user's placement key changes often, you'll be moving rows constantly, and every move risks inconsistency windows, broken foreign keys, and doubled write load.
Policy grouping determines which rules apply to a user: their region for data residency, their subscription tier for rate limits and feature flags, their tenant for access control, their cohort for experiments. These attributes change routinely and should live as metadata, not as placement logic.
A clean design keeps a small routing directory that maps user ID to shard, plus an attributes store that holds region, plan, tenant, and status. When a user upgrades or relocates, you update the attributes; placement stays put unless policy demands otherwise. That separation is what lets you answer "group users by region" without literally partitioning storage by region, which is usually a mistake for consumer products because regional populations are uneven and a small region gets a tiny, underpowered shard.
There is one legitimate exception. When a regulation or contract requires data to physically reside in a jurisdiction, residency becomes a placement constraint, and you accept uneven shard sizes as the cost. In that case region is a top-level partition, and within each region you still need a second-level grouping (user ID or tenant ID) so no single shard grows unbounded. Two-level grouping like region-then-hash is common in systems with data residency requirements.
Compare sharding key candidates on the same criteria
The honest way to choose is to score candidates against identical criteria. The table below uses the same scale for each key and reflects general design properties, not benchmarks from any particular system.
| Candidate key | Cardinality | Write spread | Single-user query locality | Multi-user/tenant query locality | Stability under attribute change | Skew risk |
|---|---|---|---|---|---|---|
| Hashed user ID | Very high | Even | Perfect | Poor (fan-out) | High | Low |
| Tenant/organization ID | High for B2B, low for B2C | Even if tenants are similar in size; skewed if a few dominate | Good if users belong to one tenant | Perfect within tenant | Medium (users can switch tenants) | High with whale tenants |
| Region/country | Low (tens to low hundreds) | Uneven | Good only if queries filter region | Moderate | Medium (users move) | Very high |
| Signup date/cohort | Medium | Uneven over time | Poor | Poor | High (never changes) | High (growth-dependent) |
| Email domain | Medium | Uneven | Good | Poor | Medium | High (consumer domains dominate) |
| Plan tier | Very low | Very uneven | Poor | Moderate | Low (changes often) | Extreme |
Two properties matter more than the rest. Cardinality must be high enough that you can split into many shards without any single value dominating: hashing a user ID gives you millions of distinct keys, while plan tier gives you three or four, which can't be split at all. And stability matters because every placement change is a migration, and migrations are where scaling projects break.
Skew is the silent killer. Tenant IDs look great until one customer is a thousand times larger than the median and pins a shard at 100% CPU while others idle. Region keys look great until your largest market holds 60% of users. If you must group by an inherently skewed attribute, plan for splitting large groups or isolating whales onto dedicated shards from day one.
Preserve locality for the second-most-important query
Pure hashing on user ID gives perfect write spread and perfect single-user locality, but it destroys tenant-level or region-level locality. If your second-most-important query is "load this organization's dashboard," hashed user IDs mean that dashboard fans out to every shard. The fix is a composite or hierarchical key rather than a single field.
Three patterns cover most cases.
Tenant-first, then hash user. Place by tenant ID, and within a tenant, distribute users by hashing their user ID across that tenant's allotted shards. This is the standard multi-tenant model: each tenant's data lives in a contiguous, splittable range, and a large tenant can be given more shards without touching anyone else. The cost is that a user who belongs to multiple organizations needs either a primary tenant (with cross-tenant access handled by fan-out) or duplicate projections.
Hash user, with a tenant index. Place each user by hashed user ID, and maintain a separate tenant-to-user index (itself sharded by tenant ID) so tenant queries resolve to a bounded list of users, then fetch across a small number of shards. This favors single-user latency and keeps tenants portable, at the cost of fan-out for tenant-wide aggregation.
Range-based user ID with time ordering. If user IDs are time-sortable (for example, snowflake-style IDs), range partitioning lets you scan recent users efficiently and archive old ranges to cheaper storage. The downside is that recent ranges take all the write traffic, so you usually need to hash within the range or add a time-bucket prefix.
The right pick follows the same fan-out logic as before. Count shards touched per request for each of your top queries. The design that keeps your top two or three queries at one or a few shards, while degrading gracefully elsewhere, is the one to build.
A worked example makes the trade-off concrete. Suppose you have 8 shards and 10,000 tenants. With tenant-first grouping, a tenant with 500 users might sit entirely on one shard, so a dashboard load touches one shard. A whale tenant with 2 million users is split across all 8, and its dashboard load touches 8 shards, which is fine because you provisioned for it. With user-ID hashing and no tenant index, every tenant dashboard touches all 8 shards, and aggregate latency across 10,000 tenants becomes the dominant cost. Same data, same hardware, very different query shape.
Handle users that belong to multiple groups
Real users span groups: a person can belong to several organizations, operate in multiple regions, and hold multiple roles. Placement can only follow one key, so you need an explicit rule for the rest.
For multi-tenant membership, name a primary tenant per user, usually the one created first or the one with the most activity, and place by that. Other memberships become indexed references. When a user's primary tenant changes, treat it as a migration and accept that it's rare. If users genuinely belong to many tenants equally, place by hashed user ID and accept tenant fan-out; duplicated projections per tenant are an option but multiply write cost.
For region, don't place by region unless residency requires it. Store region as an attribute and route reads to the nearest replica. If residency does require physical partitioning, make region a top-level partition and hash within it, as described earlier.
For status, role, or plan, never place by them. They change, they're low-cardinality, and they're the attributes most likely to be used in broad admin queries that scan across users anyway. Keep them in the metadata store and index them there.
The general principle: placement keys should be things a user is, not things a user does. Identity and tenancy are stable; behavior and entitlement are not.
Size shards and estimate capacity with reproducible math
Grouping decisions are only testable against numbers. Build a simple estimate from your own measurements rather than from generic figures, and label every input as measured or assumed.
Take four inputs: current row count per user across all tables, average row size, peak queries per second per user, and peak write bytes per second per user. Multiply and divide to get per-user storage and load, then multiply by user count to get totals, then divide by a target per-shard capacity.
For illustration, assume a measured 2 KB per user (small profile and settings), a target of 2 TB of usable storage per shard after replication and headroom, and 10 million users. That's 20 GB of user data, which fits comfortably on one shard, so storage alone gives no reason to shard. Now add 200 rows per user of activity data at 500 bytes each: that's 100 KB per user, or 1 TB total for 10 million users, which also fits on one shard but leaves less room. At 100 million users the activity data alone is 10 TB, which needs at least 5 shards at 2 TB each, before any growth headroom. The point of the exercise is that storage usually isn't the binding constraint early; write throughput and query concurrency often are, and those scale with users differently.
Do the same for throughput. If peak is 5,000 queries per second total at 100 million users, that's 0.00005 queries per user per second, which tells you nothing useful per user but everything about aggregate capacity: you need enough shards to absorb 5,000 QPS with headroom. If one shard handles 1,000 QPS comfortably at your latency target, you need at least 6 shards for peak load, and pick a power of two (8) for easier splitting later. These are illustrative inputs; substitute your own measurements and state the assumptions explicitly, because a shard count derived from real numbers is defensible and one derived from vibes is not.
Two operational cautions. First, homogeneous shards assume homogeneous tenants; if you group by tenant, size the largest tenants separately and isolate them. Second, plan for at least 2x headroom on every shard so a node failure doesn't cascade into overload on its neighbors when traffic shifts.
Route requests and maintain the assignments
Once users are grouped, every request needs to resolve a user (or tenant) to a shard. The routing layer is where most operational pain lives, so design it for change.
Directory lookup. Keep a compact mapping from placement key to shard. It can be a table in a small, highly available database, a distributed cache, or a configuration service. Two properties matter: the lookup must be fast enough to sit on the hot path, and it must be authoritative and versioned so different services agree on placement during rebalances.
Deterministic hashing with a stable function. If placement is a pure function of the key, routing needs no lookup at all: compute hash(key) mod shard_count. This is simpler and faster but rigid, because changing shard_count remaps nearly everything. Consistent hashing or fixed hash rings reduce remapping when you add shards, at the cost of slightly uneven distribution that you correct with virtual nodes.
Range or directory plus hash. The common production compromise: a directory assigns key ranges or key prefixes to shards, and within a range you hash for even spread. Moving a range is one directory update; adding capacity is a range split. This is the model to prefer when you expect rebalancing, because it makes a rebalance a metadata operation plus a bounded data copy rather than a global remap.
Whichever you choose, cache the mapping at the client with a short TTL and a version number, and handle a stale-version response by refreshing and retrying once. During a rebalance, route reads to the old shard and new shard for the moved key range, and route writes to the new shard, until the copy completes and the old range is sealed.
Rebalance and migrate without downtime
The grouping you choose determines how painful growth is, which is why the earlier sections emphasized stability and tenant-first range splits. A concrete procedure for moving a group of users to a new shard:
Prerequisites: a directory that supports range ownership and versioning, a way to identify the keys being moved (a range, a tenant, or a hash bucket), replication or change capture between shards, and application code that can read from two shards during the transition.
1: Register the new shard and mark the moving range as "migrating" in the directory at version N. 2: Copy the range's rows to the new shard while it's still serving traffic, using a consistent snapshot plus change replay for updates that arrive during the copy. 3: Verify counts and checksums per table for the moved range on both shards. 4: Switch directory ownership of the range to the new shard at version N+1, with reads allowed to serve from either copy for the transition window and writes going to the new shard. 5: Watch error rates and replication lag until the window closes; then seal the old range, remove the dual-read path, and reclaim the space.
Success check: after step 4, requests for the moved keys resolve to the new shard, and a spot check of per-user records matches pre-move checksums. Failure signal: replication lag grows without bound, checksums mismatch, or error rates rise after the switch. If lag keeps climbing through a second attempt at step 3, or if the checksum mismatch can't be attributed to identified in-flight changes, stop and bring in the database platform team rather than forcing the cutover; a half-migrated range with split ownership is far worse than a delayed rebalance.
Keep the number of concurrent migrations small, one range at a time per shard, so that a failure is contained and the rollback is obvious.
What goes wrong, and the limits of grouping
The recurring failure modes are worth naming because each one traces back to a grouping decision.
Hot partitions from low-cardinality keys. Grouping by plan, region, or cohort puts most users on a few shards. Symptom: one shard pegged at high CPU while others are idle. Fix: switch placement to a high-cardinality key and make the attribute metadata.
Fan-out from hashed single-user keys. Fine for user latency, costly for tenant or regional aggregation. Symptom: dashboard p99 latency scales with shard count. Fix: tenant-first or a tenant index.
Whale tenants. Even with good tenant grouping, one large tenant dominates a shard. Symptom: uneven disk and throughput that no key choice fixes. Fix: dedicated shards or range splits for large tenants, decided up front.
Unstable keys. Placing by attributes that change (email domain, plan, region without residency requirements) turns routine updates into migrations. Fix: placement uses only stable identity or tenancy.
Cross-shard transactions and joins. Grouping reduces but doesn't eliminate multi-shard work. Co-locate users who must transact together (same tenant, same account group) and accept that cross-group operations need sagas or application-level coordination. Don't try to solve this with a distributed transaction layer you don't need.
Rebalancing without a versioned directory. Hashing mod a fixed shard count works until you must add a shard, then everything moves at once. Fix: range-based ownership with versioned routing.
There is also a hard limit worth stating plainly: no grouping eliminates fan-out for genuinely global queries, such as analytics across all users or a search that filters by an unindexed attribute. Those belong on a separate analytical store or a replicated read model, not on the sharded transaction database. Grouping users optimizes the operational path; it doesn't make a transactional system into an analytics engine.
The last thing to accept is that the right grouping changes as the product changes. A consumer app that starts as single-user-centric may become tenant-centric when it launches a business tier; a regionally uniform product may need residency partitioning when it enters new markets. Design the directory and the metadata store so that adding a second level of grouping, or moving to tenant-first placement, is a scheduled project rather than a rewrite. The key choice is consequential, but it's the escape hatches around it that determine whether the system scales past the next order of magnitude.