EntityFrameworkCore.Sqlite.Concurrency 10.0.4

There is a newer version of this package available.
See the version list below for details.
dotnet add package EntityFrameworkCore.Sqlite.Concurrency --version 10.0.4
                    
NuGet\Install-Package EntityFrameworkCore.Sqlite.Concurrency -Version 10.0.4
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="EntityFrameworkCore.Sqlite.Concurrency" Version="10.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="EntityFrameworkCore.Sqlite.Concurrency" Version="10.0.4" />
                    
Directory.Packages.props
<PackageReference Include="EntityFrameworkCore.Sqlite.Concurrency" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add EntityFrameworkCore.Sqlite.Concurrency --version 10.0.4
                    
#r "nuget: EntityFrameworkCore.Sqlite.Concurrency, 10.0.4"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package EntityFrameworkCore.Sqlite.Concurrency@10.0.4
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=EntityFrameworkCore.Sqlite.Concurrency&version=10.0.4
                    
Install as a Cake Addin
#tool nuget:?package=EntityFrameworkCore.Sqlite.Concurrency&version=10.0.4
                    
Install as a Cake Tool

EntityFrameworkCore.Sqlite.Concurrency

NuGet Version Downloads License: MIT .NET 10

Solve SQLite Concurrency & Performance in EF Core

Tired of "database is locked" (SQLITE_BUSY) errors in your multi-threaded .NET app? Need to insert data faster than the standard SaveChanges() allows?

EntityFrameworkCore.Sqlite.Concurrency is a high-performance add-on to Microsoft.EntityFrameworkCore.Sqlite that adds automatic transaction upgrades, write serialization, and production-ready optimizations, making SQLite robust and fast for enterprise applications.

→ Get started in one line:

// Replace this:
options.UseSqlite("Data Source=app.db");

// With this:
options.UseSqliteWithConcurrency("Data Source=app.db");

Eliminates write contention errors and provides up to 10x faster bulk operations.


Why Choose This Package?

Problem with Standard EF Core SQLite Our Solution & Benefit
❌ Concurrency Errors: SQLITE_BUSY / database is locked under load. ✅ Automatic Write Serialization: BEGIN IMMEDIATE transactions and app-level locking eliminate locking errors.
❌ Slow Bulk Inserts: Linear SaveChanges() performance. ✅ Intelligent Batching: ~10x faster bulk inserts with optimized transactions and PRAGMAs.
❌ Read Contention: Reads can block behind writes. ✅ True Parallel Reads: Automatic WAL mode + optimized connection pooling for non-blocking reads.
❌ Complex Retry Logic: You need to build resilience yourself. ✅ Built-In Resilience: Exponential backoff retry with full jitter, handling all SQLITE_BUSY* variants correctly.
❌ EF DbContext not thread-safe: Sharing one context across concurrent tasks throws. ✅ IDbContextFactory support: AddConcurrentSqliteDbContextFactory<T> wires up the correct EF Core pattern for concurrent workloads.

Simple Installation

  1. Install the package:
# .NET CLI
dotnet add package EntityFrameworkCore.Sqlite.Concurrency

# Package Manager
Install-Package EntityFrameworkCore.Sqlite.Concurrency
  1. Register in Program.cs:
// For request-scoped use (controllers, Razor Pages, Blazor Server):
builder.Services.AddConcurrentSqliteDbContext<AppDbContext>("Data Source=app.db");

// For concurrent workloads (background services, Task.WhenAll, channels):
builder.Services.AddConcurrentSqliteDbContextFactory<AppDbContext>("Data Source=app.db");

Your existing DbContext, models, and LINQ queries work unchanged. Concurrent writes are serialized automatically. Reads execute in parallel.


Performance Benchmarks: Real Results

Operation Standard EF Core SQLite EntityFrameworkCore.Sqlite.Concurrency Performance Gain
Bulk Insert (10,000 records) ~4.2 seconds ~0.8 seconds 5.25x faster
Bulk Insert (100,000 records) ~42 seconds ~4.1 seconds 10.2x faster
Concurrent Reads (50 threads) ~8.7 seconds ~2.1 seconds 4.1x faster
Mixed Read/Write Workload ~15.3 seconds ~3.8 seconds 4.0x faster
Memory Usage (100k operations) ~425 MB ~285 MB 33% less memory

Benchmark environment: .NET 10, Windows 11, Intel i7-13700K, 32GB RAM


Usage Examples

Bulk Operations

public async Task ImportPostsAsync(List<Post> posts)
{
    // Bulk insert with automatic transaction management and write serialization
    await _context.BulkInsertOptimizedAsync(posts);
}

Concurrent Workloads — use IDbContextFactory

A DbContext is not thread-safe and must not be shared across concurrent operations. Inject IDbContextFactory<T> and call CreateDbContext() to give each concurrent flow its own independent instance:

public class ReportService
{
    private readonly IDbContextFactory<AppDbContext> _factory;

    public ReportService(IDbContextFactory<AppDbContext> factory)
        => _factory = factory;

    public async Task ProcessAllAsync(IEnumerable<int> ids, CancellationToken ct)
    {
        var tasks = ids.Select(async id =>
        {
            // Each task gets its own context — no EF thread-safety violation.
            // ThreadSafeEFCore.SQLite serializes writes at the SQLite level.
            await using var db = _factory.CreateDbContext();
            var item = await db.Items.FindAsync(id, ct);
            item.ProcessedAt = DateTime.UtcNow;
            await db.SaveChangesAsync(ct);
        });

        await Task.WhenAll(tasks); // ✅ All complete without "database is locked"
    }
}

Retry Wrapper

public async Task UpdateWithRetryAsync(int postId, string newContent)
{
    await _context.ExecuteWithRetryAsync(async ctx =>
    {
        var post = await ctx.Posts.FindAsync(postId);
        post.Content = newContent;
        post.UpdatedAt = DateTime.UtcNow;
        await ctx.SaveChangesAsync();
    }, maxRetries: 5);
}

Factory Pattern (without Dependency Injection)

using var context = ThreadSafeFactory.CreateContext<AppDbContext>(
    "Data Source=app.db",
    options => options.MaxRetryAttempts = 5);

return await context.ExecuteWithRetryAsync(operation, maxRetries: 5);

Configuration

builder.Services.AddConcurrentSqliteDbContext<AppDbContext>(
    "Data Source=app.db",
    options =>
    {
        options.BusyTimeout        = TimeSpan.FromSeconds(30);
        options.MaxRetryAttempts   = 3;
        options.CommandTimeout     = 300;
        options.WalAutoCheckpoint  = 1000;
        options.SynchronousMode    = SqliteSynchronousMode.Normal;
        options.UpgradeTransactionsToImmediate = true;
    });
Option Default Description
BusyTimeout 30 s PRAGMA busy_timeout — SQLite retries lock acquisition internally for this duration before surfacing SQLITE_BUSY.
MaxRetryAttempts 3 Application-level retry attempts after SQLITE_BUSY*, with exponential backoff and full jitter.
CommandTimeout 300 s EF Core SQL command timeout.
WalAutoCheckpoint 1000 pages PRAGMA wal_autocheckpoint — triggers a passive checkpoint after this many WAL frames (~4 MB). Set to 0 to disable.
SynchronousMode Normal PRAGMA synchronous — durability vs. write-speed trade-off. Normal is recommended for WAL mode.
UpgradeTransactionsToImmediate true Rewrites BEGIN to BEGIN IMMEDIATE to prevent SQLITE_BUSY_SNAPSHOT mid-transaction.

Note: Cache=Shared in the connection string is incompatible with WAL mode and will throw ArgumentException at startup. Connection pooling (Pooling=true) is enabled automatically and is the correct alternative.


FAQ

Q: How does it achieve 10x faster bulk inserts?
A: Through intelligent batching, optimized transaction management, and reduced database round-trips. Data is processed in optimal chunks with all PRAGMAs applied once per connection.

Q: Will this work with my existing queries and LINQ code?
A: Yes. Existing DbContext types, models, and LINQ queries work unchanged.

Q: Is there a performance cost for the write serialization?
A: Under 1ms per write operation. The semaphore overhead is negligible compared to actual I/O, and the WAL-mode PRAGMA tuning more than compensates for it on read-heavy workloads.

Q: Why do I need IDbContextFactory for concurrent workloads?
A: EF Core's DbContext is not thread-safe by design — it tracks state per instance. IDbContextFactory<T> creates an independent context per concurrent flow, which both satisfies EF Core's threading model and lets ThreadSafeEFCore.SQLite serialize the writes correctly at the SQLite level.

Q: Does this work on network filesystems?
A: No. SQLite WAL mode requires all connections to be on the same physical host. Do not use this library against a database on NFS, SMB, or any other network-mounted path. Use a client/server database for multi-host deployments.


Upgrade Guide

// 1. Replace raw AddDbContext + UseSqlite:
//    Before:
builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlite("Data Source=app.db"));
//    After (request-scoped):
builder.Services.AddConcurrentSqliteDbContext<AppDbContext>("Data Source=app.db");
//    After (concurrent workloads):
builder.Services.AddConcurrentSqliteDbContextFactory<AppDbContext>("Data Source=app.db");

// 2. For concurrent workloads, inject IDbContextFactory<AppDbContext>
//    and call CreateDbContext() per concurrent operation — not a shared _context.

// 3. Remove Cache=Shared from any connection string that contains it.

// 4. Remove any custom retry or locking logic — the library handles it.

System Requirements

  • .NET 10.0+
  • Entity Framework Core 10.0+
  • Microsoft.Data.Sqlite 10.0+
  • SQLite 3.35.0+

License

EntityFrameworkCore.Sqlite.Concurrency is licensed under the MIT License. Free for commercial use, open-source projects, and enterprise applications.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
10.1.1 1,758 10/5/2026
10.1.0 9,076 7/6/2026
10.0.4 886 5/2/2026
10.0.3 145 4/14/2026
10.0.2 176 1/25/2026
10.0.1 153 1/24/2026
10.0.0 160 1/24/2026

v10.0.3 — SQLITE_BUSY_SNAPSHOT fix, IDbContextFactory support, structured logging

BUGS FIXED
• SQLITE_BUSY_SNAPSHOT (extended code 517) now correctly restarts the full operation lambda
 instead of retrying the same statement — the only correct fix for a stale WAL read snapshot.
• Exponential backoff now uses full jitter ([baseDelay, 2×baseDelay]) to prevent thundering
 herd when multiple threads contend simultaneously.
• Cache=Shared in the connection string now throws ArgumentException at startup — it silently
 broke WAL mode semantics in prior versions.
• Invalid SqliteConcurrencyOptions values (MaxRetryAttempts ≤ 0, negative BusyTimeout, etc.)
 now throw ArgumentOutOfRangeException at startup instead of silently misbehaving.

NEW FEATURES
• AddConcurrentSqliteDbContextFactory<T> — registers IDbContextFactory<T> with all concurrency
 settings. Use this for Task.WhenAll, background services, Channel<T> consumers, and any
 workload that creates concurrent database operations. DbContext is not thread-safe; the factory
 pattern gives each concurrent flow its own independent instance.
• Structured logging: pass ILoggerFactory (or let DI resolve it) to get Warning logs for
 SQLITE_BUSY/SQLITE_BUSY_SNAPSHOT events, Error logs for SQLITE_LOCKED, and Debug logs for
 BEGIN IMMEDIATE upgrades — all through your existing logging pipeline.
• GetWalCheckpointStatusAsync — runs PRAGMA wal_checkpoint(PASSIVE) and returns a typed
 WalCheckpointStatus with IsBusy, TotalWalFrames, CheckpointedFrames, and CheckpointProgress.
 Call periodically to detect long-running readers blocking WAL reclamation before it degrades
 read performance.
• TryReleaseMigrationLockAsync — detects and optionally clears a stale __EFMigrationsLock
 row left behind by a crashed migration process. Prevents indefinite blocking on Database.Migrate()
 in multi-instance deployments.
• SynchronousMode option — configures PRAGMA synchronous (Off / Normal / Full / Extra).
 Default remains Normal (recommended for WAL: safe after app crash, fast writes).
• UpgradeTransactionsToImmediate option — opt out of the BEGIN → BEGIN IMMEDIATE rewrite
 if you manage write transactions explicitly yourself. Default remains true.

NO BREAKING CHANGES — all existing call sites compile and behave correctly without modification.