Writing many rows — bulk insert, batch updates and data migrations
The rest of Rask.Data: domain modelling · storage — queries, conventions and the database.
Every change a person makes goes through an aggregate's own method (operations), so its rules hold. This page is for the other kind of write: a load of thousands of rows a seed or an import makes, and a statement the database runs over every matching row at once. Each says what it skips, so it is a choice you make knowing it.
Writes over many rows
Five writes on every aggregate type, for when one row at a time is the wrong shape:
await Pairing.DeleteWhere(p => p.Pump == pumpId); // one DELETE
await Period.UpdateWhere(p => p.Id == id, s => s.SetProperty(p => p.Closed, true)); // one UPDATE
await Fueling.UpdateEach(f => codes.Contains(f.DriverChip), f => f.Match(plan)); // each loaded, changed, saved
var card = await Card.FindOrCreate(c => c.Number == number, () => Card.FromFile(number)); // the one, or a new one
var loaded = await Transaction.Import(lines, line => Loaded(file, line),
o => o.OnInvalid = ImportFailure.Collect); // set aside, not stopped
A set write — UpdateWhere, DeleteWhere — is one statement, so no row is loaded and the aggregate's methods
do not run: it is for an aggregate no rule is about — a flag, a stamp, an infrastructure row (a login
session, a pairing a pump re-sends). What a save keeps it still keeps:
- the tenant and soft-delete filters (an
ISoftDeletesaggregate'sDeleteWherestampsDeletedAtinstead); UpdatedAtstamped andVersionbumped byUpdateWhere, so a form read before it is refused as stale;- the declared locks (
LockedBy): a row whose parent is locked is refused — the old parent before the statement, the oneUpdateWheremoved it to after it, still inside the transaction it rolls back — every parent the rows hold read under an update lock first (UPDLOCK, HOLDLOCK/FOR UPDATE), so a close cannot slip in between the check and the statement; anUpdateWherethat sets only the lock'sExcept(…)columns passes, as a save of them alone does; - the unique and still-referenced messages, under the field a form shows;
- the data-changed notices a live page repaints on, after the commit;
- the one-aggregate rule, counted as one write of the type.
What it cannot keep it refuses, rather than write past it: a Rules() or DeletionRules() asks each row in C# —
whether another aggregate holds it, what the change touches — as
does a lock declared on a child the delete would cascade to. So UpdateWhere on an aggregate that declares
Rules() throws and names X.UpdateEach(where, x => x.Step(…)), which loads each one, runs its step and asks its
rules; and DeleteWhere on one that overrides DeletionRules() (or a child's lock) throws and names X.Delete(id).
A b.Prune(…) of such an aggregate is refused as the app starts, for the same reason.
Both run in a Db.Transaction of their own, or join the one in progress, and hand back how many rows they wrote.
Joined, they are part of that one transaction and no other: the same connection as everything else the block writes —
the aggregates' entries, a SaveChangesAsync() on the app's own context — at the block's isolation, rolled back with it,
their notices sent once it commits:
await Db.Transaction(async () =>
{
await Pairing.DeleteWhere(p => p.Pump == pump); // joins the block's transaction
db.AddRange(rows.Select(r => Pairing.Of(pump, r)));
await db.SaveChangesAsync(); // the same transaction
}, manyAggregates: "A pump's pairings are replaced as one", isolation: IsolationLevel.Serializable);
UpdateEach goes through the aggregate: the keys the predicate matches are read first, then each aggregate is
loaded whole, changed by its own method and saved — its rules, events and notices as for one — batchSize (500) to a
transaction, each batch saved in one go. A batch says why it writes many aggregates (each is valid on its own), so
OneAggregatePerTransaction lets it through. A refused batch rolls back alone and the refusal is thrown; the batches
before it stay committed, so the change should be one that can run twice — which an event handler's is anyway.
FindOrCreate is the one-root "find it, or make it" — Rails' find_or_create_by, Laravel's firstOrCreate: the
one aggregate the predicate matches is handed back as it is stored, loaded whole and with nothing written, or the
factory makes a new one and it is saved through its rules. A predicate that matches two is refused. A change is the
aggregate's own operation and Save() after it, so there is no "make it or change it" write beside it:
var fueling = await Fueling.FindOrCreate(f => f.Pump == r.Pump && f.Number == r.Number, () => Fueling.Taken(r));
fueling.AsThePumpHoldsIt(r.Moment);
await fueling.Save();
| Rails | Laravel | Rask |
|---|---|---|
Card.find_or_create_by(number: n) |
Card::firstOrCreate(['number' => $n]) |
await Card.FindOrCreate(c => c.Number == n, () => Card.FromFile(n)) |
Back the predicate with a unique index. Two callers that both find none both build one; the index lets the first insert
through and refuses the second — and FindOrCreate takes that refusal as the race lost, reads the match again and hands
the second caller the row that won, so both get the same one and no error. Only a refusal by a unique index whose
columns the predicate names is taken so (the tenant aside, which the filter already pins); another index, Rules()
or any other rule surfaces as from any save. Inside a Db.Transaction the refusal surfaces too — the database has
refused that transaction, and PostgreSQL has ended it.
The tenant and soft-delete filters apply to the match: another tenant's row, or a soft-deleted one, never matches. A unique index that still holds the soft-deleted row then refuses the new one under its field; filter the index to the rows not deleted when a deleted one may be made again.
Import is the large load through the factory (BulkInsert is the one past it): each row is made
by the aggregate's factory and saved through its rules — Rules(), the unique checks, LockedBy, events —
BatchSize (500) to a transaction, each batch from an empty change tracker, so memory stays flat. A row refused by
its factory or its rules stops the import by default (the batches before stay committed); ImportFailure.Collect
sets it aside in result.Failures — its Index among the rows, the row, the RaskValidationException — and saves
the rest: the refused batch is run again a row at a time, each in a transaction of its own, which holds on every
database alike (a unique violation ends PostgreSQL's transaction). result.Inserted counts what was saved; a loader whose rows may meet what an earlier one stored
takes each through FindOrCreate and the aggregate's operation instead. A factory may be called again for a retried batch: it builds, it
does not write. Collect commits a batch at a time, so inside a Db.Transaction it is refused; Stop there makes
the import part of that transaction.
Pruning old rows
A table that only grows — sign-in sessions, processed files, a queue's done rows — is cleared by a prune: declared
in the aggregate's own Configure, run by Rask.Jobs on a schedule, as Laravel's Prunable
is.
public sealed class LoginSession : Aggregate<Guid>
{
public static void Configure(EntityTypeBuilder<LoginSession> b) =>
b.Prune(s => s.ExpiresAt < Clock.Now).Daily.At(3, 0);
}
public sealed class QueuedFile : Aggregate<int>, IBelongsTo<Company>
{
public static void Configure(EntityTypeBuilder<QueuedFile> b) =>
b.Prune((f, keep) => f.Done && f.DoneAt < Clock.Now - keep, keep: 30.Days, batchSize: 500);
}
The second reads how long a row is kept as keep, and the code's 30.Days is only the default: the app sets it, with
the schedule and an off switch, in one place, by the aggregate's name.
app.Configure(c => c.Jobs.Configure(o =>
{
o.Prune["QueuedFile"].Keep = 60.Days; // read at each run
o.Prune["QueuedFile"].At = new TimeOnly(4, 0); // daily at 04:00 instead
o.Prune["LoginSession"].Every = 30.Minutes; // or every half hour
o.Prune["Visit"].Off = true; // not on the schedule at all
}));
The same from configuration — Rask:Jobs:Prune:QueuedFile:Keep is 60.00:00:00, …:At is 04:00, …:Every is
00:30:00, …:Off is true (Rask__Jobs__Prune__QueuedFile__Keep=60.00:00:00 in the environment); code wins. Rask's
own tables are pruned the same way, and configured the same way:
| Prune | Deletes | Keeps by default | Runs by default |
|---|---|---|---|
Prune:Job |
a job that ran — done, refused or stopped; a dead letter never | 7 days | daily at 03:00 |
Prune:OutboxMessage |
a published message; a dead letter never | 7 days | daily at 03:00 |
Prune:QueuedMail |
a sent mail; a dead letter never | 30 days | daily at 03:00 |
Prune:Session |
a session that ended or expired | 1 day after that | every hour |
Prune:CacheEntry |
an entry past its expiry | nothing past it | every 5 minutes |
an app's own b.Prune(…) |
what its predicate matches | its keep: (the docs use 30 days) |
its schedule step, else daily at 03:00 |
Every prune deletes 1000 rows to a statement unless its declaration says batchSize:. The database log store
(LogEntry, 30 days and at most 100,000 rows, swept hourly) is not a prune: see what still sweeps on its
own.
- The schedule is a recurring job's:
.Every(1.Hour),.Daily.At(3, 0),.Weekly.On(…).At(…),.Monthly.On(1).At(6, 0),.RunOnFirstStart(),.Named("…")— read in the app'sClock.Zone. Without one it runs daily at 03:00. It runs asPrune:{Aggregate}, and the operator console lists it with the other recurring jobs and how long it keeps its rows:daily at 03:00, keeps 7 days. A configuredAtorEveryreplaces the declared step, andOffleaves it off the schedule; both are read when the app starts. - The predicate is read at every run, not when the model is built:
Clock.Nowin it is the time of the run, andClock.Fake(…)in a test moves the cutoff.keepis the setting as it is at that run — an edited appsettings value applies on the next one, no restart — and reaches the database as a parameter, so every value reads the same statement. - A setting that does nothing fails the start: a name no
b.Prune(…)of the model answers to (o.Prune["Recipt"]), or aKeepfor a prune whose predicate reads none. - It deletes in batches of
batchSize(1000), the first rows by key, each oneDELETEstatement in a transaction of its own, until a batch comes back short — so a first run over a million old rows never holds one transaction over them all. Each batch is the set write's statement: the pages showing the rows hear of it after the commit, and a row another still refers to fails the run, as it failsDeleteWhere. Narrow the predicate, or let the reference cascade. - It is infrastructure, so it runs across every tenant: one declaration clears every tenant's expired rows, inside
Tenant.Across(). A rule for one tenant only belongs in the predicate. - It deletes for good. On an
ISoftDeletesaggregate the soft-delete filter is lifted and the rows are removed, not stamped — the predicate sees the stamped rows beside the live ones, sob.Prune(d => d.DeletedAt < Clock.Now - 90.Days)clears only what was retired long enough ago, andb.Prune(d => d.SavedAt < cutoff)would remove live rows too. - What one statement cannot keep, the boot refuses: an aggregate — or a child a cascade deletes — that declares
DeletionRules(), a heardXDeletedorLockedByasks each row in C#, which aDELETEwould skip. Rask does not fall back to loading each row throughX.Delete(id): a rule that may refuse a row makes the delete a decision of the domain's, which a job of your own that callsX.Delete(id)words better, and a prune that loaded every row would cost what its one line does not read as. - It needs the job queue. A
RaskAppalways has it. A hand-wired host's prune withoutAddRaskJobs<TContext>()fails the boot, naming the call — except a battery's own (the table above), which is simply not run there.
Bulk insert
EF Core answers the bulk update and delete shapes with ExecuteUpdate/ExecuteDelete, but its own
plan puts bulk inserts out of scope —
so seeding, importing and migrating data is left to every application to hand-roll. BulkInsert is that
code, written once:
await db.BulkInsert(products); // on the context
await db.Products.BulkInsert(products); // or the set
await db.BulkInsert(products, o => o.BatchSize = 10_000);
It runs through the context, so nothing above stops being true: CreatedAt/UpdatedAt are stamped and
each entity's domain events are published, exactly as for an ordinary save. What changes is the shape of the
work — the rows are added and saved in batches (5,000 by default), change detection is off for the duration,
and the change tracker is cleared between batches.
That last part is the point. The naive AddRange + one SaveChanges keeps every entity tracked until the
end, so a large load's memory grows with the row count and each save re-walks what the previous ones already
wrote. Over 100,000 rows on SQLite:
| approach | time | allocated |
|---|---|---|
SaveChanges per row |
5.48 s | 2,472 MB |
AddRange + one SaveChanges |
1.22 s | 1,307 MB |
BulkInsert |
976 ms | 1,105 MB |
BulkInsert, SkipChangeTracking |
406 ms | 141 MB |
The last row is the fast path below; the rest is what batching alone buys.
What it asks — and what it does not
BulkInsert is for a seed, a migration, a copy of rows already checked: it is not a Create, and it does not
ask the domain as one does.
Rule a Supply.Create(…) asks |
Supply.New(…) + Save() in one Db.Transaction, Supply.Import(…) |
BulkInsert |
BulkInsert, SkipChangeTracking |
|---|---|---|---|
the roles of Create (b.Operation(nameof(Create), roles: …), else b.Writes(roles: …)) |
asked | not asked | not asked |
| the tenant — stamped, another tenant's row refused | asked | asked | asked |
| a value object's rules | asked as it is made, by the factory | the caller's: whatever made the row | the caller's |
Rules() and the validation attributes |
asked | asked | not asked |
| the domain events | published after the commit | published after the commit | refused: a row carrying one throws |
A loader that must hold to every rule — an import a person starts, rows from a partner — builds each row with the aggregate's factory and saves it through the aggregate:
await Db.Transaction(async () =>
{
foreach (var row in rows)
{
await Supply.New(row).Save(); // Create's roles, the tenant, Rules(), the events — as Supply.Create(row)
}
}, manyAggregates: "One file's supplies are loaded together");
or Supply.Import(rows, row => Supply.New(row)) above, which does the same a batch to a transaction. A refusal
anywhere in the block rolls the whole load back, and its events are published once each after the commit.
Where the transaction sits
Each batch commits on its own by default. That is deliberate: SQLite has exactly one write lock, so wrapping a long import in a single transaction makes every other writer in the application wait for the whole thing, and the WAL has to hold every uncommitted page until the end. Committing per batch hands the lock back between batches. The cost is that a failure part-way leaves the batches that already committed — for a seed or an import, usually the retryable outcome you want.
When the load really must be all-or-nothing, ask for it:
await db.BulkInsert(products, o => o.SingleTransaction = true);
Domain events wait for the commit — in that mode and inside any transaction around the load (yours, or a
Db.Transaction): every batch's events are published once the whole load commits, and none when it rolls
back. A rollback gives each entity its events back (and clears a key the database generated for a row that is
gone), so a retrying strategy that runs the load again inserts and announces each row once. Durable handlers'
outbox rows are written in the same transaction as the batches.
The fast path
Most of what is left after the batching is the change tracker itself — materialising an entry per row,
walking them on save, then throwing them away. SkipChangeTracking writes the rows straight to the provider
instead:
await db.BulkInsert(products, o => o.SkipChangeTracking = true);
The shape it writes in depends on what a statement costs. On SQLite it is one prepared INSERT whose
parameters are rebound per row: a local file has no round trip, and a statement packed with many rows is quadratic
to bind there. On PostgreSQL, SQL Server and MySQL every statement is a round trip, so it packs up to 1,000 rows
into each INSERT … VALUES (…), (…) — fewer on SQL Server, whose request carries at most 2,100 parameters. Against
PostgreSQL 17 with 1 ms of added latency, 10,000 rows took 136 ms and allocated 11.6 MB that way, against 225 ms
and 99 MB through the change tracker and 20.1 s one row at a time (PostgresBulkInsertBenchmarks, run with
scripts/run-bulk-insert-benchmarks-local.sh, which starts the server on Testcontainers). Another provider gets the per-row shape, which is correct
everywhere and slow wherever there is a network.
It is opt-in because of what it skips: no ISaveChangesInterceptor runs — not Rask.Data's, and not any
you registered. The writer stamps CreatedAt/UpdatedAt itself (from the same TimeProvider the auditing
interceptor uses, so a frozen test clock agrees across both paths), but nothing stands in for the rest.
Entities carrying domain events are rejected rather than inserted with their events undelivered, and an
outbox never sees the load.
Anything the writer cannot map faithfully throws and names the reason rather than writing wrong rows: a
store-assigned integer key (its value only exists after the insert), a store-computed column, a shadow
property, a navigation (nothing walks the graph here, so related rows would vanish), or an inheritance
hierarchy. A client-assigned key — the Entity<Guid> shape Rask entities use, where the factory sets Id —
is fine, and left unset it is reported rather than written as Guid.Empty.
Two more rules follow from how it works:
- The context must have no pending changes. The tracker is cleared as the load runs, so unsaved work would be discarded rather than swept into the first batch. It throws rather than lose it — save first.
- An ambient transaction still owns the commit. Called inside your own
BeginTransaction, the load joins it and commits nothing itself, so it composes with surrounding work.
Under a retrying execution strategy (Rask:Sqlite:Retry:Enabled, or UseRaskSqlite(sp, o => o.Retry.Enabled = true)), a SingleTransaction
load is one retryable unit and a lazy sequence is buffered so the retry can re-enumerate it; the default
per-batch mode lets EF retry each batch on its own, which is both cheaper and free of replay.
A running number
b.Numbered(…) — beside b.Computed(…), which it pairs with.
A number every row has among its group — the fuelings of a pistol, counted by moment — kept by Rask in every save, with no SQL in the app:
static void Configure(EntityTypeBuilder<Fueling> b)
{
b.Computed(f => f.CountedAt, f => f.ModifiedPistolId ?? f.PistolId);
b.Numbered(f => f.Sequence, within: f => f.CountedAt, by: f => new { f.Moment, f.Number, f.Id },
skip: f => f.MergedParentId != null)
.Same(f => f.ParentId) // a split part has its whole one's number
.SkipWhen<Distribution, FuelingId>((f, shares) => shares.Any(s => s.FromFuelingId == f.Id), s => s.FromFuelingId);
}
- What it keeps. Each row of a group is numbered 1, 2, 3 … in the order
bysays, the first member first; a rowskipleaves out has none (null), and the rows after it close up. A row whose group is null has none. - When. A save that adds, deletes or moves a row — changes its group, a member of
by,skiporSame— numbers each group it touched anew from the earliest place it touched, counting on from the last number before it, and writes only the numbers that changed — before the save's transaction commits, so a rollback takes them back too. The rows the context holds are told their new numbers and stay unchanged. Same(f => f.ParentId): a row that names another takes that row's number instead of a place of its own, and follows it when it moves.SkipWhen<TOther, TRow>(when, row): another table's rows leave a row out — a fueling distributed from is not counted. A save that adds, changes or deletes aTOtherrow numbers anew the group of the rowrownames.- One numbering of a group at a time, on every database. SQL Server takes
sp_getapplockowned by the save's transaction and PostgreSQLpg_advisory_xact_lock, per group, in a sorted order, before the rows go out; SQLite's one writer already keeps saves apart. Saves racing into one group leave it numbered without a gap or a twin. - A computed group or order. A
withinorbymember that is ab.Computed(…)column —CountedAtabove — is read as what it is computed from: an added row is numbered in the group its values put it in, and a change to a member it is computed from (ModifiedPistolId) moves the row, numbering anew both the group it leaves and the one it joins. A value C# cannot compute from the row (a division by zero) is read back from the database once the row is written, still before the commit. byis a member, or several as an anonymous type (new { f.Moment, f.Id }): plain values, or one-value value objects compared by their value. The number is a whole number — nullable when a row can have none — or a one-value value object over one. The entity's key is one column. A rawExecuteUpdatepasses no save, so it numbers nothing.
Rows written past a save — a raw ExecuteUpdate, a migration's SQL, an import straight into the table, rows stored
before the numbering was declared — are numbered anew on the type itself:
await Fueling.Renumber(pistolId); // one group
await Fueling.Renumber([pistolId, otherId]); // several
var changed = await Fueling.RenumberAll(); // every group, and no number for a row in none: the data repair
Each group is numbered whole, from its first row, by the rules a save numbers it by — by, skip, Same, SkipWhen —
and only the numbers that changed are written; the answer is how many. It runs in a Db.Transaction of its own, or joins
the one in progress, under the same per-group lock a save takes, so a save into a group being numbered waits for it. The
tenant filter applies — a tenant's call numbers its own rows — and the pages showing them are told once it commits. A
group is a value of the type within names (a string pistol id above); another type, or a type that declares no
numbering, is refused.
Batch update and delete
For work the database can do on its own — a retention sweep, a flag every matching row gets — the aggregate's own set writes are one statement over every matching row, with nothing loaded and nothing tracked, so a million rows cost one round trip rather than a million objects:
await Product.UpdateWhere(p => p.Discontinued, s => s
.SetProperty(p => p.Active, false)
.SetProperty(p => p.Price, p => p.Price * 0.9m)); // the arithmetic happens in SQL
await Draft.DeleteWhere(d => d.SavedAt < cutoff); // an ISoftDeletes aggregate's rows are stamped instead
Unlike EF Core's ExecuteUpdateAsync and ExecuteDeleteAsync underneath, they keep the conventions: UpdatedAt is
stamped and Version bumped, an ISoftDeletes aggregate's delete stamps DeletedAt rather than removing the row, the
tenant and soft-delete filters apply, the declared locks and the unique and referenced-row messages are asked, and the
pages showing the rows are told. A change a rule decides is never one of these — it goes through the aggregate's
operation, row by row, with UpdateEach.
A raw db.Set<T>().Where(…).ExecuteUpdateAsync(…) skips all of that — no stamp, no version bump, no events, no audit,
and a DELETE where a soft delete was meant — so on an aggregate the build points at it
(RASK187) and its quick-fix rewrites it into X.UpdateWhere(…) / X.DeleteWhere(…). It stays
for a table that is no aggregate: a migration step's, or one an adopted schema
keeps beside the model.
Data a migration moves
A schema change is a migration — rask db add, applied as the app starts
(migrations apply themselves on start). The rows already in the table
are moved one of two ways, by what the change means:
A rule decides the new value — a status a period's state implies, a value object tightened so an old value no longer passes. Run the aggregate's own operation over each row, from a job, so every row is changed by the rule that will change it from now on, its version checked and its events raised:
public sealed record ReopenPeriods : IJob; public sealed class ReopenPeriodsHandler : IJobHandler<ReopenPeriods> { public async Task Handle(ReopenPeriods job) { foreach (var id in await Period.Where(p => p.ClosedAt == null).Select(p => p.Id)) { await Period.Reopen(id); // the operation's own entry: one aggregate, one transaction } } }One aggregate per transaction keeps a long move from holding a lock over the whole table, and a job that stops half-way runs again over the rows still to do. A stored row an operation would refuse is told so by name, rather than rewritten past its rule.
Nothing decides it — a new column every old row gets the same value in, a column renamed. That is the migration's own: a default on the added column, which fills the rows already there, or a batch update the job runs once.
A tightened rule does not make a stored row unreadable: a value object is loaded without being validated, and a save asks a property's rules only once that property is changed (what every save asks), so old rows open, and are put right as they are next edited.
Moving data in C# with b.Data
A schema change that needs its data moved — a link table filled from the column it replaces, a value split in two —
moves it through the app's own aggregates, not in SQL. A migration's Up adds a data step:
public partial class TankPistols : Migration
{
protected override void Up(MigrationBuilder b)
{
b.CreateTable(/* …what `rask db add TankPistols` wrote… */);
b.Data(async () =>
await Tank.UpdateEach(_ => true, async t => t.Draw(await Pistol.Where(p => p.TankId == t.Id).Select(p => p.Id))));
}
}
- It runs after the whole schema is migrated, with the model the app has now — at the app's start (when
migrations apply themselves), from
dotnet App.dll rask db migrate, and afterrask db update(which runsdotnet ef database update, then the app'srask db migrate). Every tenant's rows are in reach: the step runs insideTenant.Across(). The rules and events of every save it makes run as they do anywhere else. - It runs once, whole or not at all. Each migration whose steps have run is recorded in a
__RaskDataStepstable beside EF Core's history, made by the first run that has a step to record — a database whose migrations declare none never gets it. A migration's steps run in one transaction with the row that records them, under the lock EF Core migrates under: a step that fails rolls back what it wrote and stops the start with its error (the schema stays migrated, and the step runs again on the next start), a crash can never leave a finished step unrecorded, and a second instance starting beside the first waits for it and finds the step done. A migration applied by plaindotnet ef database update(which runs no C#) has its steps run the next time the app migrates. - Still write it so a second run is harmless. The schema step and its data step are not one transaction, and a step that reaches outside the database (a file, a mail, another service) is not rolled back with it.
- The model is today's. A step names only what the model still has; the change that drops a column a step reads deletes the step from its migration (the migration itself stays, as history).
- In the SQL of
dotnet ef migrations scripta step is a comment — it is C#, and the app runs it.