Data layer and SQL
Transactions, concurrency and consistency
All or nothing: writing several changes safely, and two people editing the same record.
Understand the concept
A transaction makes several changes one indivisible unit: either all are saved or none. In EF Core a single SaveChanges call already runs inside a transaction; a post and its tags added in the same call are written or rolled back together. When several SaveChanges calls must be combined, an explicit transaction is started.
Transactions must be short. An open transaction holds locks and occupies a connection; sending e-mail or calling an external API inside it makes other requests wait and drains the pool. External effects happen after the database work has completed successfully.
Concurrency is two users changing the same record at once. With ‘last write wins’ one change silently disappears. Optimistic concurrency prevents this: a version (rowversion) is read with the record and the update applies only if the version has not changed. If it has, EF Core throws DbUpdateConcurrencyException and the user can be told ‘this record changed while you were editing’.
Half-written or silently overwritten data is among the hardest bugs to notice.
Making HTTP calls or sending e-mail while a transaction is open.
One topic. Three levels of depth.
db.Posts.Add(post);
db.PostTags.AddRange(tags);
await db.SaveChangesAsync(ct); // ikisi birlikte yazılır veya hiçbiriA single SaveChanges runs in its own transaction.
This page connects to no real server or database. Code samples are illustrative for .NET 8, Next.js and SQL Server; timings are example values in the simulation, not measurements. Try samples only in your own development environment; never share real connection strings, tokens or passwords.
Try it yourself first.
The same post is open in two tabs. One changes the title, the other the content, and they save in turn. What happens without a version check, and with one?
Show the solution and explanation
Yoksa: ikinci kayıt, ilk sekmenin yüklediği eski başlığı da yazar → başlık değişikliği kaybolur.
Varsa: ikinci kayıt 409 alır; kullanıcı güncel hali görüp değişikliğini yeniden uygular.Optimistic concurrency turns a lost update from a silent bug into a visible conflict.