📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your design has outgrown a single database. How do you partition and shard the data? Explain how you choose a shard key, what hot keys are and how you deal with them, how you reshard when you need more capacity, and what happens to queries that need data from more than one shard. Use Azure SQL and Cosmos DB as examples.

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.

Senior Theory Advanced azure-sql cosmos-db partitioning scalability sharding system-design

🎯 Key points

  • Shard only after caching, replicas and vertical scale; it is a one-way door for queries and operations
  • Shard key comes from the dominant access pattern: high cardinality, even load, most queries hit one shard (e.g. TenantId)
  • Hash (even spread, no range scans) vs range (range scans, hot ranges) vs directory / shard map (flexible, extra lookup)
  • Hot keys: split big tenants to their own shard, salt keys, hierarchical partition keys in Cosmos DB, cache hot reads
  • Resharding: consistent hashing or many virtual partitions mapped to fewer physical nodes; move partitions, not rows; dual-write or copy-then-cut-over
  • Cross-shard queries: scatter-gather, a separate read model or search index, avoid cross-shard transactions (saga / outbox)
  • Cosmos DB: logical partition limit 20 GB and 10,000 RU/s; physical partitions split automatically
  • Azure SQL: elastic database tools shard map manager or database-per-tenant in elastic pools; table partitioning is not sharding

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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) % 4 and 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."


Strategies

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

Choosing the shard key

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

Azure options

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

Production example

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.

🔍 What the interviewer is checking

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

  • Treats sharding as a last resort and a one-way door
  • Justifies the key with cardinality, load distribution and single-shard queries
  • Has a concrete resharding plan (virtual partitions, shard map, copy and cut over)
  • Moves cross-shard queries to read models and avoids distributed transactions

Red flags

  • hash % N with no plan to change N
  • Partitions by date or status for a write-heavy table
  • Assumes joins and unique constraints still work across shards

📚 Learn in depth

1. Why sharding exists

A 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

2. Hashing and resharding

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.

3. Moving data safely

  1. Copy the partition to the new shard while the old one still serves.
  2. Catch up with change tracking / change feed.
  3. Briefly block writes for that partition (or use a version fence), finish catch-up.
  4. Flip the shard map entry; clients refresh their cached map.
  5. Delete from the old shard after a soak period.

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.

4. Hot keys

  • Isolate: put a whale tenant on its own shard via the directory.
  • Salt: write to key#0..key#15, read all 16 and merge (counters, likes).
  • Hierarchical keys: Cosmos DB /tenantId/userId lets a tenant exceed 20 GB because the second level spreads it over physical partitions.
  • Cache: hot reads served from Redis or the edge never reach the shard.

5. Cross-shard work

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)

6. Operations cost

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.

7. Try it yourself

  1. Write a function that maps 100,000 keys with % 4 and % 5 and count how many move; then repeat with 1,024 virtual slots.
  2. Take a real tenant table, run SELECT TenantId, COUNT(*) ... GROUP BY TenantId ORDER BY 2 DESC and compute what share the top 1% holds.
  3. Create a Cosmos DB container with a poor partition key (/country) in the emulator, load data and inspect partition key ranges and 429 rates.
  4. Implement a scatter-gather query over three databases with Task.WhenAll and a 2 s timeout that returns partial results.
  5. Draw the cut-over sequence for moving one tenant between shards and mark where writes are blocked.

💻 Code

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);
}

⚠ Common mistakes

  • Mistake: Sharding before trying cheaper options. Why it is wrong: It permanently complicates joins, constraints, migrations and reporting. Instead: Exhaust indexing, caching, read replicas (read-write splitting) and vertical scale, and shard when the write path is the limit.
  • Mistake: Using 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.
  • Mistake: Picking a key with low cardinality or skew (country, status, date). Why it is wrong: It creates hot partitions and size limits. Instead: Use a high-cardinality key aligned with the main access pattern, and handle known whales separately.
  • Mistake: Using 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.
  • Mistake: Confusing SQL Server table partitioning with sharding. Why it is wrong: Table partitioning stays on one server and doesn't add write capacity. Instead: Use it for maintenance and archiving; shard across databases for scale.
  • Mistake: Doing cross-shard transactions or joins on the request path. Why it is wrong: It reintroduces coordination and kills latency and availability. Instead: Keep requests single-shard; use sagas, outboxes and read models for the rest.
  • Mistake: Forgetting global uniqueness and IDs. Why it is wrong: Identity columns collide across shards and unique emails can't be enforced locally. Instead: Use UUIDv7 or Snowflake IDs and a small global lookup for unique values.
  • Mistake: Monitoring only the system as a whole. Why it is wrong: Averages hide one hot shard or one whale tenant; you find out when it throttles. Instead: Track load, storage and latency per shard and per tenant (Azure Monitor per database, Cosmos DB normalised RU consumption by partition key range), and alert before a shard or logical partition nears its limit.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions Azure SQL Hyperscale, elastic pools or table partitioning Why: Checks they know the SQL Server scaling options before and instead of sharding
    How to answer

    I start with numbers: data size and growth, hot versus cold data, read/write ratio and tenant distribution. Then:

    • Partitioning (by date) is mainly a manageability tool: 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.
    • Archive cold data to cheaper storage or a history database.
    • Tenant layout: shared schema for many small tenants, database per tenant in an elastic pool for isolation, a hybrid for large tenants.
    • Hyperscale for one large database (up to 128 TB, fast scaling, read replicas); elastic pools for many small databases sharing compute.

    Shard only when scale-up, read scale-out and archiving are exhausted: it moves complexity into the application.

  2. When: Candidate mentions consistent hashing or virtual partitions Why: Checks they can apply the same partitioning ideas to a cache cluster
    How to answer

    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.

  3. When: Candidate mentions replicas or Cosmos DB consistency Why: Checks they understand what consistency a partitioned, replicated store gives
    How to answer

    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.

🛠 Real-world problems: how you handle them

Three whale tenants were slowing down everyone in a shared database
Situation
[Practice-management] SaaS with [1,800] tenants in one [Azure SQL Business Critical] database of [~2 TB]; [3] tenants produced [40%] of the writes.
Signals
Small tenants reported slow screens at month end; p99 rose to [1.2 s]; Query Store showed lock waits and log write waits; CPU sat above 85% for hours.
Investigation
Grouped Query Store and Application Insights telemetry by tenant claim to find the load share per tenant; back-of-the-envelope showed one more large tenant would exceed the top tier; reviewed queries to confirm >98% were single-tenant.
Resolution
Short term, moved month-end batch jobs off-peak. Then introduced a shard map: the 3 whales moved to dedicated databases using copy, change-tracking catch-up and a cut-over per tenant; the rest moved to [4] pooled databases by tenant slot.
Prevention
Per-tenant load dashboards, an alert when any tenant exceeds [10%] of a shard's load, migrations run through an elastic job across all shards in CI, and an ADR on the tenant shard key.

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.

↩ Usually asked after

More in Senior Design Focus

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me