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

📚 Interview question

Your SQL Server database is heading towards several terabytes and many tenants. How would you design it to scale? Discuss table partitioning, archiving old data, multi-tenant database layouts, and choosing between Azure SQL Hyperscale and elastic pools.

A staff-level architecture question on scaling SQL Server and Azure SQL: partitioning (and what it does not do), archiving with partition switching, tenant layouts, Hyperscale versus elastic pools, read scale-out and sharding.

Staff / Architect Architecture Expert architecture azure-sql elastic-pools hyperscale partitioning sql-server

🎯 Key points

  • Start from workload numbers: size, growth, read/write ratio, hot vs cold data
  • Partitioning is mainly for manageability, not a guaranteed speed-up
  • Partition switching and sliding windows make archiving metadata-only
  • Partition column must be in unique indexes; queries need partition elimination
  • Hyperscale: one big database up to 128 TB, fast scale, named read replicas
  • Elastic pools: many small databases sharing compute; Hyperscale elastic pools GA since September 2024
  • Tenant layout: shared, schema or database per tenant; residency in Australia East/Southeast where required
  • Measure before and after (hot-set size, log rate, per-tenant CPU); shard only as a last resort

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"I'd start by refusing to design for 'terabytes' in the abstract. I want the current size and monthly growth, how much of it is touched in a normal week, the read/write ratio, peak transactions per second, and how tenants are distributed: are there ten big ones and a thousand tiny ones? In most systems I've seen, 80 to 90 percent of the data is cold history, and that changes everything.

For large time-based tables, I'd partition by month. I'm careful how I sell it: partitioning is a manageability feature first. It lets me switch an old partition out to an archive table as a metadata operation, rebuild indexes per partition, and with a sliding window keep the hot table a fixed size. It only helps query speed if queries filter on the partition column so the engine can eliminate partitions, and every unique index has to include the partition key. For tenancy, I'd keep many small tenants in a shared schema with a TenantId leading the keys and row-level security as a safety net, and put large or regulated tenants in their own databases in an elastic pool. That's also where data residency comes in: Australian government customers may need their data in Australia East with geo-replication to Australia Southeast.

For the platform, Hyperscale fits one big database: storage up to 128 terabytes, fast scaling because compute is separate from page servers, and named replicas for reporting. Elastic pools fit many small databases with spiky, uncorrelated load, and since 2024 there are Hyperscale elastic pools too. For example, at [company] we [had a 6 TB orders database where 85% was older than two years]. We [partitioned by month and switched old partitions to an archive database], which [cut the hot table to 900 GB and halved backup and index maintenance time]. The mistake I see is jumping to sharding first; it buys scale by moving cross-shard queries, transactions and rebalancing into the application. Shrink the hot set before you split the database."


The levers, in the order I reach for them

Lever Solves Costs Doesn't solve
Indexes, query tuning Most performance problems Write overhead Storage growth
Archive cold data Hot-set size, backups, maintenance Archive queries are slower or separate Write throughput
Partitioning Archiving/purging, per-partition maintenance Key design constraints, plan subtleties Slow queries without elimination
Scale up / Hyperscale Size, compute, fast scaling Cost; single write node Unlimited write throughput
Read scale-out / named replicas Reporting load Replica lag Writes
Elastic pools Many tenant databases with uneven load Noisy neighbours within a pool One huge tenant
Sharding Write throughput beyond one node Cross-shard queries, rebalancing, app complexity Nothing, if you didn't need it

Hyperscale vs elastic pools (as of November 2026)

Hyperscale single database Elastic pool (GP/BC or Hyperscale)
Shape One large database Many databases sharing vCores
Size Up to 128 TB Per pool limits; Hyperscale pools up to 100 TB total, 25 databases (GA September 2024)
Strengths Fast backups/restores (snapshots), scale compute quickly, up to 4 HA replicas and named replicas Cost-efficient for many tenants with uncorrelated peaks
Watch Single primary for writes; log generation rate limits Noisy neighbours; per-database max settings

Tenant layouts

Layout Isolation Cost per tenant Operations
Shared schema + TenantId Logical (filters, RLS) Lowest One migration; tenant export is harder
Schema per tenant Medium Low Migrations per schema; object count grows
Database per tenant (pooled) Strong Medium Fleet migrations, monitoring per database
Hybrid Per tenant tier Varies Two code paths in routing, one schema

Production example

In a SaaS platform [you can describe], a [6] TB database spent [11] hours on weekly index maintenance and restores took [9] hours. Monthly partitioning with switch-out to an archive database reduced the hot set to [900] GB; maintenance dropped to [2] hours and point-in-time restores of the hot database to under [1] hour.

🔍 What the interviewer is checking

Checks whether the candidate can reason about database scale with numbers and trade-offs rather than buzzwords, and knows what each Azure SQL option actually solves.

Green flags

  • Asks for workload numbers first
  • Explains partitioning as manageability, with elimination and key constraints
  • Describes sliding-window archiving with SWITCH
  • Matches Hyperscale and elastic pools to workload shapes, with current limits
  • Treats sharding as a last resort and names its costs

Red flags

  • "Partition it and it will be fast"
  • Jumps straight to sharding or NoSQL
  • No mention of retention, residency or operations

📚 Learn in depth

1. Partitioning mechanics

Partition function  (RANGE RIGHT on OrderedAt: 2026-01-01, 2026-02-01, ...)
        │
Partition scheme    (maps each partition to a filegroup; on Azure SQL DB all go to PRIMARY)
        │
Table / indexes     (created ON the scheme; "aligned" when indexes use the same scheme)

  P1 <2026-01 | P2 Jan | P3 Feb | ... | Pn current   ← inserts land here
  • Available in all editions since SQL Server 2016 SP1 and in Azure SQL Database.
  • A unique index (including the clustered PK) on a partitioned table must contain the partition column, so PKs often become (OrderId, OrderedAt).
  • Partition elimination needs a predicate on the partition column the optimiser can use; queries by CustomerId alone touch every partition (one seek per partition), which can be slower than an unpartitioned table.

2. Sliding window

monthly job:
  1. SPLIT a new empty partition at the head (next month)
  2. SWITCH the oldest partition OUT to an empty staging table with identical structure
  3. MERGE the now-empty boundary at the tail
  4. Move staging rows to the archive (another table, database or Parquet in storage)

SWITCH is a metadata change: milliseconds, regardless of row count, provided indexes are aligned and the target is empty with matching constraints. Splitting a non-empty partition is expensive, which is why you always split empty ones ahead of time.

3. Archiving options

Target Query access Cost
Archive table in the same database Full T-SQL Same storage price, but smaller hot indexes
Separate archive database (lower tier or serverless) Cross-database queries via the app Cheaper compute
Parquet in Azure Data Lake / Fabric Analytics engines Cheapest; not OLTP-queryable
Temporal history table with retention policy FOR SYSTEM_TIME Automatic cleanup

Retention must follow policy and law: the Privacy Act 1988 (APP 11.2) expects personal information to be destroyed or de-identified when no longer needed, so archiving is not "keep forever".

4. Hyperscale architecture

 Compute (primary) ──log──► Log service ──► Page servers (each owns a slice of data) ──► Azure Storage
     │                                  ▲
 HA replicas / named replicas ─────────┘  (read pages from page servers, apply log)

Because storage is separate, backups are storage snapshots (near-instant), restores are fast and size-independent in practice, and compute scales quickly. Writes still go through one primary, and log generation rate is the throughput ceiling.

5. Elastic pools

A pool buys a block of vCores shared by its databases, each with min/max per-database settings. It pays off when tenant peaks do not coincide. A large tenant with steady load should leave the pool.

6. Sharding

Splitting tenants (or key ranges) across databases needs a shard map (catalogue database), routing in the app, fleet-wide migrations, cross-shard reporting (a warehouse) and a tenant-move procedure. It is the right answer at real scale and the wrong first step.

Try it yourself

  1. Create a partition function and scheme by month, a partitioned Orders table with 10 million rows, and run a query with and without a date predicate; compare "Actual Partitions Accessed" in the plan.
  2. Practise a sliding window: split, switch out, merge. Time the switch.
  3. Try creating a unique index without the partition column and read the error.
  4. Price a Hyperscale database and an elastic pool for your workload in the Azure pricing calculator for Australia East.
  5. Write the routing code for database-per-tenant with a catalogue table and SqlConnectionStringBuilder.

💻 Code

Monthly partitioning with a sliding window for archiving.

CREATE PARTITION FUNCTION pfOrdersMonthly (datetime2(3))
    AS RANGE RIGHT FOR VALUES ('2026-01-01', '2026-02-01', '2026-03-01');
CREATE PARTITION SCHEME psOrdersMonthly
    AS PARTITION pfOrdersMonthly ALL TO ([PRIMARY]);   -- Azure SQL DB: PRIMARY only

CREATE TABLE dbo.Orders
(
    OrderId    bigint IDENTITY NOT NULL,
    TenantId   int NOT NULL,
    CustomerId int NOT NULL,
    OrderedAt  datetime2(3) NOT NULL,
    Total      decimal(19,4) NOT NULL,
    CONSTRAINT PK_Orders PRIMARY KEY CLUSTERED (OrderId, OrderedAt)  -- must include the partition column
) ON psOrdersMonthly (OrderedAt);

CREATE INDEX IX_Orders_Tenant_OrderedAt ON dbo.Orders (TenantId, OrderedAt) ON psOrdersMonthly (OrderedAt); -- aligned

-- Staging table for switch-out: same columns, same indexes, same filegroup, empty.
CREATE TABLE dbo.Orders_SwitchOut
(
    OrderId bigint NOT NULL, TenantId int NOT NULL, CustomerId int NOT NULL,
    OrderedAt datetime2(3) NOT NULL, Total decimal(19,4) NOT NULL,
    CONSTRAINT PK_Orders_SwitchOut PRIMARY KEY CLUSTERED (OrderId, OrderedAt)
);
CREATE INDEX IX_Orders_SwitchOut_Tenant_OrderedAt ON dbo.Orders_SwitchOut (TenantId, OrderedAt);

-- Monthly job: add next month (empty), switch the oldest out, remove its boundary.
ALTER PARTITION SCHEME psOrdersMonthly NEXT USED [PRIMARY];
ALTER PARTITION FUNCTION pfOrdersMonthly() SPLIT RANGE ('2026-04-01');
ALTER TABLE dbo.Orders SWITCH PARTITION 1 TO dbo.Orders_SwitchOut;   -- metadata only
ALTER PARTITION FUNCTION pfOrdersMonthly() MERGE RANGE ('2026-01-01');
-- then copy Orders_SwitchOut to the archive and truncate it

Database-per-tenant routing for large tenants, shared database for the rest.

namespace Saas.Data;

using Microsoft.Data.SqlClient;

public sealed record TenantPlacement(int TenantId, string? DedicatedDatabase);

public interface ITenantCatalogue
{
    Task<TenantPlacement> GetAsync(int tenantId, CancellationToken ct);
}

public sealed class TenantConnectionFactory(ITenantCatalogue catalogue, string sharedConnectionString)
{
    public async Task<SqlConnection> OpenAsync(int tenantId, CancellationToken ct)
    {
        var placement = await catalogue.GetAsync(tenantId, ct);
        var builder = new SqlConnectionStringBuilder(sharedConnectionString);
        if (placement.DedicatedDatabase is { } db)
        {
            builder.InitialCatalog = db; // isolated tenant in the elastic pool
        }
        var connection = new SqlConnection(builder.ConnectionString);
        await connection.OpenAsync(ct);
        return connection; // shared-database tenants still rely on TenantId filters + row-level security
    }
}

⚠ Common mistakes

  • Mistake: Partitioning to "make queries faster". Why it is wrong: without elimination, queries touch every partition and can get slower. Instead: partition for archiving and maintenance; tune queries with indexes.
  • Mistake: Partitioning on a column queries don't filter by. Why it is wrong: no elimination, and the key still has to be in every unique index. Instead: choose the column that drives retention and range queries (usually a date).
  • Mistake: Splitting a non-empty partition at month end. Why it is wrong: moves rows, logs heavily and locks. Instead: always keep an empty partition ahead and split ahead of time.
  • Mistake: Keeping all history in the hot OLTP database forever. Why it is wrong: bigger backups, restores and indexes, and a Privacy Act retention problem. Instead: a retention policy with archive and purge.
  • Mistake: Sharding before using scale-up, archiving and read replicas. Why it is wrong: permanent application complexity. Instead: exhaust the simpler levers first, with numbers.
  • Mistake: Putting one heavy tenant in an elastic pool with hundreds of small ones. Why it is wrong: noisy neighbour; everyone suffers its peaks. Instead: move it to its own database or tier.
  • Mistake: Assuming Hyperscale removes the write ceiling. Why it is wrong: there is still one primary and a log rate limit. Instead: measure log generation and plan sharding only if writes outgrow it.

🏛 Senior insight: trade-offs

Scaling a relational database is mostly about shrinking the hot set and matching the platform to the tenant shape. Partitioning, archiving and read replicas handle most growth; Hyperscale handles big single databases; elastic pools handle many small ones; sharding is the last resort because its cost lands in every feature afterwards.

Option When it fits Cost When not to
Partition + sliding window Large time-based tables with retention rules Key and index constraints, a monthly job to own Small tables, queries without date filters
Hyperscale One database beyond a few TB or needing fast scale and restores Higher price than General Purpose Many tiny tenant databases
Elastic pool Hundreds of small tenant databases Fleet operations One dominant tenant
Sharding Write volume beyond one primary Routing, cross-shard reporting, rebalancing Before simpler levers are exhausted

Measure before deciding: growth per month, hot-set size (sys.dm_db_partition_stats by date range), log generation rate, peak DTU/vCore use, and per-tenant resource use from Query Store.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate discusses tenant layouts. Why: Checks depth on multi-tenant isolation, cost and operations.
    How to answer

    There are three models.

    • Shared schema: every row has a TenantId and EF Core applies a filter. Cheapest, one migration, but isolation is only as good as your code, and tenants compete for resources.
    • Schema per tenant: little real isolation gain for a lot of EF Core friction (model caching per schema, migrations per schema). Rarely worth it.
    • Database per tenant: the strongest isolation, per-tenant restore, region and scale, made affordable by Azure SQL elastic pools. The cost is operations: migrating and monitoring N databases.

    Most SaaS products end up hybrid: small tenants share, large or regulated tenants get their own database, routed through a tenant catalogue. The trade-off is isolation and flexibility against cost and operational complexity.

  2. When: Candidate mentions moving large tenants to their own database. Why: Checks the migration mechanics with minimal downtime.
    How to answer

    Provision the new database from the current migration bundle, then copy the tenant's rows table by table in foreign-key order (SqlBulkCopy or BCP, keeping key values), and verify with counts and checksums. Track changes made during the copy (a ModifiedAt watermark, change tracking or CDC), then take a short write freeze for that tenant, apply the final delta, flip the catalogue entry to the new connection and clear the catalogue cache. Keep the source rows read-only for a rollback window, then delete them. Rehearse on a copy and measure the freeze time first.

  3. When: Candidate changes the primary key to include the partition column. Why: Checks understanding of clustered key choices.
    How to answer

    I separate two decisions: the primary key (logical identity) and the clustered key (physical row order). A good clustered key is narrow, unique, static and ever-increasing, because it is copied into every non-clustered index.

    • int/bigint IDENTITY: 4 or 8 bytes, ordered inserts; the default for most OLTP tables. Watch int exhaustion at about 2.1 billion.
    • GUIDs: 16 bytes, generated anywhere. NEWID() is random and causes page splits; NEWSEQUENTIALID() is ordered but only as a column default. .NET's Guid.CreateVersion7() is time-ordered, but SQL Server sorts uniqueidentifier starting from the last six bytes, so v7 values still insert randomly.
    • Natural keys change; I use a surrogate key plus a unique constraint on the natural key.

    Trade-off: ordered keys insert cheaply but can create last-page contention and are guessable.

🛠 Real-world problems: how you handle them

6 TB orders database: maintenance and restores outgrow the window
Situation
A multi-tenant SaaS platform on Azure SQL [Business Critical, Australia East] had a [6] TB database growing [150] GB a month. Most queries touched the last [90] days; [85]% of rows were older than two years.
Signals
Weekly index maintenance ran [11] hours and overlapped business hours; a restore test took [9] hours, breaking the [4]-hour RTO; storage was approaching the tier maximum; a few large tenants caused CPU spikes for everyone.
Investigation
Measured row counts and size by month with `sys.dm_db_partition_stats` and a date histogram; Query Store showed [95]% of reads filtered by recent dates; per-tenant CPU from Query Store tags showed [3] tenants using [40]% of CPU; log generation rate was well under the Hyperscale limit.
Resolution
Partitioned the largest tables by month (PK changed to include `OrderedAt`), switched partitions older than two years to an archive database on a cheaper tier, and set a monthly sliding-window job. Moved the three largest tenants to their own databases in an elastic pool. Later moved the main database to Hyperscale for snapshot backups.
Prevention
Retention policy agreed with legal (APP 11.2), monthly sliding-window job with alerting, capacity dashboard (size by month, per-tenant CPU), and an ADR describing when a tenant moves to a dedicated database.

How to tell it (STAR)

**S:** At [company] our main database had reached [6] TB, maintenance ran [11] hours and a restore test blew our [4]-hour RTO. **T:** As [lead/architect], I had to make it manageable without a rewrite. **A:** I measured the hot set and found [85]% of rows were older than two years and three tenants used [40]% of CPU. I designed monthly partitioning with a sliding window to an archive database, agreed the retention policy with legal, and moved the three big tenants to their own pooled databases. **R:** The hot database dropped to [900] GB, maintenance to [2] hours, restores to under [1] hour, and noisy-neighbour incidents stopped.

↩ Usually asked after

More in Database Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me