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

📚 Interview question

How do you choose primary keys in EF Core on SQL Server? Compare identity integers with GUIDs (random, sequential and Guid.CreateVersion7()), and explain composite keys, alternate keys, sequences and HiLo.

Covers key strategies in EF Core on SQL Server: identity columns, random versus sequential GUIDs and Version 7 GUIDs, clustered index fragmentation, composite and alternate keys, database sequences and the HiLo pattern.

Mid-Level Theory Intermediate clustered-index ef-core guid hilo primary-keys sql-server

🎯 Key points

  • int/bigint identity: small, ordered, but value known only after INSERT
  • Random GUID (NEWID/Guid.NewGuid) as clustered key → page splits and fragmentation
  • By convention a Guid key is ValueGeneratedOnAdd and the SQL Server provider fills it client-side with SequentialGuidValueGenerator
  • SQL Server sorts uniqueidentifier by its last 6 bytes first, so Guid.CreateVersion7() is not sequential in SQL Server order
  • Ever-increasing keys can cause last-page insert contention (PAGELATCH_EX) at very high concurrency; OPTIMIZE_FOR_SEQUENTIAL_KEY helps
  • Composite keys via HasKey(x => new { x.A, x.B }); alternate keys via HasAlternateKey (unique constraint, FK target)
  • Sequences (HasSequence) and UseHiLo() reserve blocks of ids to cut round trips; gaps are normal
  • Clustered key can differ from PK: IsClustered(false) on a GUID PK

⏱ 30-second answer

Identity int/bigint keys are small (4/8 bytes) and always increasing, so inserts append to the end of the clustered index; the downside is the value only exists after the INSERT. GUIDs can be created anywhere (offline clients, merges, ids before saving) but are 16 bytes, and random GUIDs as a clustered key cause page splits and fragmentation.

  • EF Core's SQL Server provider generates sequential GUIDs client-side by default, ordered the way SQL Server compares uniqueidentifier.
  • Guid.CreateVersion7() is time-ordered by .NET's byte order, but SQL Server compares the last 6 bytes first, so it is not sequential in a SQL Server index.
  • Composite keys (HasKey(x => new { x.A, x.B })), alternate keys (unique, can be FK targets), sequences and HiLo (UseHiLo()) cover the rest.

The trade-off: identity is simplest and smallest; GUIDs buy distribution at the cost of size and care with clustering.

🗣 Full answer (senior)

How I would answer this in an interview

"My default for a single SQL Server database is an int or bigint identity. It's 4 or 8 bytes, it's ever-increasing so the clustered index only grows at the end, and every nonclustered index carries the clustering key, so a small key keeps all indexes small. The limitation is that the database assigns the value, so I don't have the id until SaveChanges, and EF Core has to read it back after each insert.

I choose GUIDs when ids must be created outside the database: offline mobile clients, events that carry the id before they are persisted, merging data from several sources, or not wanting guessable ids in URLs. The trap is random GUIDs as the clustered key. Each insert lands on a random page, pages split, fragmentation climbs and the buffer pool fills with half-empty pages. EF Core already helps: for a Guid key on SQL Server it generates sequential GUIDs client-side, ordered the way SQL Server compares them. The subtle point is Guid.CreateVersion7(). It's time-ordered in .NET's byte order, but SQL Server compares a uniqueidentifier starting with the last six bytes, so a v7 GUID still inserts all over the index. If I need a GUID primary key from somewhere else, I make the PK nonclustered and cluster on something ordered, like an identity or a created timestamp.

Beyond that: composite keys for join tables, alternate keys for natural identifiers like an order number that other tables reference, and HiLo when I insert many rows and want ids client-side without a GUID. HiLo reserves a block of ids from a sequence, say 10 at a time, so a batch of inserts needs one round trip for ids instead of one per row. The mistake I see is picking GUIDs 'because microservices' without checking how they cluster."


Comparison

Key Size Generated Clustered insert pattern Use when
int identity 4 B Database, on INSERT Append Default, < 2.1 billion rows
bigint identity 8 B Database Append High-volume tables
Random GUID 16 B Anywhere Random → page splits Never as clustered key
EF sequential GUID 16 B Client (EF Core) Mostly append Ids needed before save
NEWSEQUENTIALID() 16 B Database default Append (per server restart) DB-generated GUIDs
Guid.CreateVersion7() 16 B Anywhere Not ordered in SQL Server Cross-system ids; non-clustered PK
HiLo / sequence 4–8 B Client reserves blocks Append Many inserts, ids before save

Composite and alternate keys

Fluent API Schema
Composite PK HasKey(e => new { e.StudentId, e.CourseId }) PK on two columns
Alternate key HasAlternateKey(o => o.OrderNumber) Unique constraint; FK target allowed
Unique index HasIndex(o => o.Email).IsUnique() Unique index; not an FK target in EF

Production example

At [company] an events table with random GUID clustered keys reached [99%] fragmentation within a day and insert latency rose from 2 ms to 25 ms at [3,000] inserts/second. Making the GUID PK nonclustered and clustering on a bigint identity brought inserts back to ~2 ms and halved the index size.

🔍 What the interviewer is checking

Checks whether the candidate understands the physical consequences of key choices in SQL Server, not just the C# type.

Green flags

  • Explains clustering key size and page splits
  • Knows EF Core's sequential GUID generator
  • Knows the SQL Server uniqueidentifier ordering subtlety
  • Can explain HiLo and alternate keys

Red flags

  • "GUIDs are always better for scale"
  • No awareness of fragmentation

📚 Learn in depth

1. Why the clustering key matters

In SQL Server the clustered index is the table, ordered by the clustering key. Every nonclustered index row stores the clustering key as its row locator.

Nonclustered IX_Orders_CustomerId: (CustomerId, <clustering key>)
  4-byte int key  →  small IX rows
  16-byte GUID    →  +12 bytes on every row of every index

2. Random inserts and page splits

append-only (identity):  [p1 full][p2 full][p3 filling...]
random (NEWID):          [p1 50%][p2 50%][p7 50%][p3 50%] ← splits everywhere

A page split moves half a page to a new page, logs both, and leaves two half-full pages. Fragmentation hurts range scans and memory efficiency.

3. How SQL Server compares uniqueidentifier

SQL Server orders by byte groups in the order 10–15, then 8–9, 6–7, 4–5, 0–3. The most significant part is the last six bytes. NEWSEQUENTIALID() and EF Core's SequentialGuidValueGenerator increment those bytes, so they sort well. A Version 7 GUID puts its 48-bit timestamp in the first six bytes, which SQL Server treats as least significant.

4. HiLo

sequence EntityFrameworkHiLoSequence INCREMENT BY 10
client asks once: NEXT VALUE → 1  → uses 1..10 locally
after 10 inserts: NEXT VALUE → 11 → uses 11..20

Ids are known before SaveChanges, inserts batch better, and gaps after restarts are normal. Gaps are fine for keys; never use keys as invoice numbers that must be gapless.

5. Identity read-back

With identity keys EF Core uses OUTPUT INSERTED.Id (or MERGE for batches) to read generated values and fix up FKs of dependents in the same SaveChanges.

Try it yourself

  1. Insert 1 million rows into three tables keyed by NEWID(), NEWSEQUENTIALID() and identity; compare sys.dm_db_index_physical_stats.
  2. Generate 10 Guid.CreateVersion7() values, insert them and ORDER BY the column; observe the order.
  3. Configure UseHiLo() and watch the SQL log for sequence calls during a batch insert.
  4. Add an alternate key and reference it from another entity with HasPrincipalKey.

💻 Code

Key configurations side by side.

namespace Shop.Infrastructure;

using Microsoft.EntityFrameworkCore;

public sealed class Order
{
    public long Id { get; set; }                 // bigint identity (default for integer keys)
    public required string OrderNumber { get; set; }
}

public sealed class DeviceEvent
{
    public Guid Id { get; set; }                 // created on the device, before it reaches us
    public long Sequence { get; set; }           // clustered, ever-increasing
}

public sealed class Shipment
{
    public int Id { get; set; }                  // HiLo: ids known before SaveChanges
    public string OrderNumber { get; set; } = "";
}

public sealed class ShopDbContext(DbContextOptions<ShopDbContext> options) : DbContext(options)
{
    protected override void OnModelCreating(ModelBuilder b)
    {
        b.Entity<Order>(e =>
        {
            e.HasAlternateKey(o => o.OrderNumber);   // unique, and other tables may reference it
            e.Property(o => o.OrderNumber).HasMaxLength(20);
        });

        b.Entity<DeviceEvent>(e =>
        {
            e.HasKey(x => x.Id).IsClustered(false);  // GUID PK, but not the clustered index
            e.Property(x => x.Id).ValueGeneratedNever();
            e.Property(x => x.Sequence).UseIdentityColumn();
            e.HasIndex(x => x.Sequence).IsClustered();
        });

        b.Entity<Shipment>(e =>
        {
            e.Property(s => s.Id).UseHiLo("ShipmentIds");  // INCREMENT BY 10 by default
            e.HasOne<Order>().WithMany()
             .HasForeignKey(s => s.OrderNumber)
             .HasPrincipalKey(o => o.OrderNumber);          // FK to the alternate key
        });
    }
}
CREATE SEQUENCE [ShipmentIds] START WITH 1 INCREMENT BY 10 NO MINVALUE NO MAXVALUE NO CYCLE;
CREATE TABLE [DeviceEvent] (
    [Id] uniqueidentifier NOT NULL,
    [Sequence] bigint NOT NULL IDENTITY,
    CONSTRAINT [PK_DeviceEvent] PRIMARY KEY NONCLUSTERED ([Id])
);
CREATE CLUSTERED INDEX [IX_DeviceEvent_Sequence] ON [DeviceEvent] ([Sequence]);

⚠ Common mistakes

  • Mistake: Using Guid.NewGuid() or NEWID() as a clustered primary key. Why it is wrong: random inserts cause page splits and fragmentation. Instead: leave EF Core's default sequential generator on, or make the PK nonclustered.
  • Mistake: Assuming Guid.CreateVersion7() is index-friendly in SQL Server. Why it is wrong: SQL Server compares the last six bytes first, so v7 ordering is lost. Instead: use EF Core's sequential generator or cluster on another column.
  • Mistake: Setting ValueGeneratedNever() without a clear owner for the id. Why it is wrong: it is right when ids come from outside (a device, an event, a natural key), but if no code assigns one every row gets Guid.Empty or 0 and the second insert fails with a duplicate key; it also changes how Update/Attach decide between insert and update, because a set key no longer means "existing row". Instead: use it only when the caller always supplies the id, assign it in the constructor, and cover it with a test.
  • Mistake: Ignoring last-page insert contention on an identity clustered key at very high insert rates. Why it is wrong: every insert targets the same last page, so threads queue on PAGELATCH_EX waits and throughput flattens. Instead: turn on OPTIMIZE_FOR_SEQUENTIAL_KEY = ON for the index (SQL Server 2019+, Azure SQL), and only consider hash-partitioning or a different key if waits remain high.
  • Mistake: Using int for a table that will exceed 2.1 billion rows. Why it is wrong: changing a PK type later means rebuilding every referencing table. Instead: bigint for high-volume tables.
  • Mistake: Using identity or sequence values as gapless business numbers. Why it is wrong: rollbacks and HiLo blocks leave gaps. Instead: a separate number generated in the business transaction.
  • Mistake: Exposing sequential integer ids in public URLs. Why it is wrong: enumeration attacks (IDOR) are easier. Instead: authorise every access, and consider a public GUID alternate key.

🏛 Senior insight: trade-offs

Key choice is a physical design decision with a 10-year lifetime. The question I ask is "who creates the id, and when?" If only the database creates rows, identity wins. If ids must exist before the database sees the row (offline clients, events that carry their id, data merged from several regions or systems, idempotent retries where the client resends the same id), use GUIDs, but separate the logical key (GUID PK) from the physical order (clustered index) when the GUID isn't SQL Server-sequential.

HiLo deserves a precise answer. It scales well because each process reserves a block (10 ids by default, often raised to 100+ for bulk loads) with one NEXT VALUE FOR call, so ids are known before SaveChanges and inserts batch without OUTPUT read-back. The costs: gaps whenever a process restarts with an unused block, ids that are only roughly ordered across instances, every writer (including scripts and other services) must draw from the same sequence, and the sequence itself is one more object in the migrations.

Option When it fits Cost When not to
Identity int/bigint Single database, server-created rows Id only after insert; last-page contention at extreme rates Offline or distributed creation
EF sequential GUID Ids before save, EF Core as the only writer 16 bytes in every index Ids generated by other systems
GUID PK nonclustered + identity clustered External GUIDs (v7, NewGuid) Extra index Small tables where it doesn't matter
HiLo Large batch inserts with int keys Gaps, a shared sequence Gapless numbering, many non-EF writers

Measure with sys.dm_db_index_physical_stats (fragmentation, page density), sys.dm_os_wait_stats for PAGELATCH_EX, and insert latency in Application Insights before and after.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions HiLo or sequences. Why: Checks understanding of client-side key generation.
    How to answer

    UseHiLo() makes EF Core get keys from a database sequence (EntityFrameworkHiLoSequence by default, INCREMENT BY 10). One round trip reserves a block of values; EF Core then hands out ids from that block in memory before SaveChanges, so entities have real keys early and inserts batch without an OUTPUT of identity values. The database still guarantees uniqueness, because every instance reserves its own block from the same sequence. Trade-offs: gaps (a restarted process or a recycled context loses the rest of its block), ids are not in insert order across instances, the sequence becomes shared schema every writer must use (raw SQL inserts must call NEXT VALUE FOR), and a block too small means more sequence calls while a block too large means bigger gaps. Size the block to insert throughput: UseHiLo("OrderSeq") with the sequence's increment set, for example, to 100 for bulk imports.

  2. When: Candidate mentions fragmentation or page splits. Why: Checks link between key design and storage engine behaviour.
    How to answer

    A clustered index stores rows in key order. A random Guid.NewGuid() key sends every insert to a random page, so full pages split (half the rows move to a new page, both writes are logged), page density drops towards ~50–70%, and the index is fragmented. More pages means more I/O and buffer-pool memory for every scan and range seek, and inserts touch pages spread over the whole index instead of a hot last page that stays in cache. Measure it with sys.dm_db_index_physical_stats (avg_fragmentation_in_percent, avg_page_space_used_in_percent, page_count), the Page Splits/sec counter, transaction log growth and insert latency in Query Store. Fixes: an IDENTITY/bigint clustered key, sequential GUIDs (EF Core's default SequentialGuidValueGenerator for SQL Server, NEWSEQUENTIALID(), or Guid.CreateVersion7()), or keep the random GUID as a non-clustered unique key and cluster on something else.

🛠 Real-world problems: how you handle them

Insert latency climbs as a GUID-keyed events table fragments
Situation
An ingestion API on Azure SQL [Business Critical, 8 vCores] stores [3,000] device events per second in a table whose clustered primary key is a `Guid` assigned on the device with `Guid.NewGuid()`.
Signals
Application Insights shows the SQL dependency for the insert rising from 2 ms to 25 ms p95 over a day; Azure SQL log IO and CPU climb; the nightly index rebuild takes 40 minutes.
Investigation
Checked `sys.dm_db_index_physical_stats`: 98% fragmentation, 55% page density on the clustered index. The Page Splits/sec counter was in the thousands. Query Store showed the insert plan was trivial, so the cost was in the storage engine, not the query. Reviewed the EF Core configuration: `ValueGeneratedNever()` on the GUID key because devices assign ids.
Resolution
Immediate: rebuilt the index with FILLFACTOR 80 to reduce splits for the day. Real fix: a migration that made the GUID PK nonclustered and added a `bigint` identity column with a clustered index, keeping the device GUID as the identity used by the API.
Prevention
An architecture decision record on key strategy; a code review checklist item for GUID keys; an Azure Monitor alert on insert p95 and a weekly fragmentation report.

How to tell it (STAR)

**S:** Our ingestion API at [company] wrote [3,000] device events a second into Azure SQL, keyed by GUIDs the devices generated. **T:** Insert latency was creeping up every day and I was asked to find out why before peak season. **A:** I ruled out the query with Query Store, then found 98% fragmentation and half-empty pages on the clustered index. The random GUID was the clustering key. I kept the GUID as the logical primary key but made it nonclustered, added a bigint identity as the clustered index, and shipped it as a migration in a quiet window. **R:** Insert p95 went from 25 ms back to about 2 ms, the table shrank by [40%], and we wrote a key-strategy ADR so new tables start right.

↩ Usually asked after

More in EF Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me