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.
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.
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.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.
"My default for a single SQL Server database is an
intorbigintidentity. 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 untilSaveChanges, 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
Guidkey on SQL Server it generates sequential GUIDs client-side, ordered the way SQL Server compares them. The subtle point isGuid.CreateVersion7(). It's time-ordered in .NET's byte order, but SQL Server compares auniqueidentifierstarting 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."
| 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 |
| 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 |
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.
Checks whether the candidate understands the physical consequences of key choices in SQL Server, not just the C# type.
Green flags
Red flags
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
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.
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.
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.
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.
NEWID(), NEWSEQUENTIALID() and identity; compare sys.dm_db_index_physical_stats.Guid.CreateVersion7() values, insert them and ORDER BY the column; observe the order.UseHiLo() and watch the SQL log for sequence calls during a batch insert.HasPrincipalKey.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]);
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.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.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.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.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.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.
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.
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.
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.
Last updated 23 Nov 2026.