SQLite is a popular choice for .NET applications that need local database storage without installing or managing a separate database server. It works particularly well for desktop applications, command-line utilities, background services, local development tools, and applications that need to operate offline.
However, SQLite has an important concurrency limitation: only one write transaction can modify a database at a time. This becomes noticeable when multiple processes access the same database file.
Consider a desktop application that stores project information in SQLite while a background service periodically updates task statuses. A second command-line utility might also read the same database. All three processes can access the database, but simultaneous write operations may encounter database locking errors.
SQLite provides Write-Ahead Logging, commonly called WAL mode, to improve concurrency between readers and writers. Instead of modifying the main database file directly for every transaction, SQLite first records changes in a separate write-ahead log file.
WAL mode can make multi-process database access more efficient, but it does not remove every locking restriction. Applications still need to manage transactions, connection lifetimes, busy timeouts, and checkpoint operations carefully.
In this article, we will explore how SQLite WAL mode works, how to enable it in a .NET application, and how to handle concurrent database operations safely when multiple processes use the same database.
Understanding SQLite Concurrency
SQLite allows multiple processes to connect to the same database file, provided they can access it through a supported filesystem.
In its traditional rollback-journal mode, SQLite uses locking to coordinate database reads and writes. A write transaction may need to prevent other connections from accessing the database in ways that conflict with the update.
This can become a bottleneck when several processes access the database at the same time.
For example, imagine the following application setup:
A desktop application reads project information.
A background service updates task statuses.
A command-line utility inserts new development tasks.
All three processes use the same SQLite database file.
If the background service is writing while another process attempts a conflicting operation, the second operation may have to wait or receive a database-busy error.
The important distinction is that SQLite supports multiple concurrent readers, but it does not allow multiple simultaneous write transactions to modify the same database.
WAL mode improves how readers and writers work together, but it still allows only one active writer at a time.
What Is SQLite Write-Ahead Logging?
In the traditional rollback-journal approach, SQLite records information needed to restore the original database state if a transaction fails.
With Write-Ahead Logging, changes are first written to a separate log file. Once a transaction commits, its changes are available to subsequent readers, even before they are copied back into the main database file.
When WAL mode is enabled, SQLite typically uses three files:
File | Purpose |
|---|---|
app.db | Main SQLite database |
app.db-wal | Stores committed changes that have not yet been checkpointed |
app.db-shm | Coordinates access to the WAL index between connections |
The WAL file contains database changes from committed transactions. The shared-memory file helps connections coordinate access to the WAL index.
The main database file is updated later through a process called checkpointing.
The basic workflow looks like this:
Application starts a write transaction
|
v
Changes are written to WAL file
|
v
Transaction commits
|
v
New readers can see committed changes
|
v
Checkpoint copies changes to main database
|
v
WAL file can be reused or resetThis approach allows readers to continue accessing a consistent database snapshot while a writer appends new changes to the WAL file.
It is particularly useful when an application has frequent reads and occasional writes.
Enabling WAL Mode in a .NET Application
Let's create a small .NET console application that uses SQLite in WAL mode.
Create the project:
dotnet new console -n SqliteWalDemo
cd SqliteWalDemoInstall Microsoft.Data.Sqlite:
dotnet add package Microsoft.Data.SqliteCreate a database initializer that enables WAL mode.
using Microsoft.Data.Sqlite;
public class DatabaseInitializer
{
private readonly string _connectionString;
public DatabaseInitializer(string databasePath)
{
_connectionString =
new SqliteConnectionStringBuilder
{
DataSource = databasePath,
DefaultTimeout = 10
}.ToString();
}
public string ConnectionString => _connectionString;
public void Initialize()
{
using var connection =
new SqliteConnection(_connectionString);
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = """
PRAGMA journal_mode = WAL;
CREATE TABLE IF NOT EXISTS Tasks
(
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Title TEXT NOT NULL,
IsCompleted INTEGER NOT NULL DEFAULT 0,
CreatedAt TEXT NOT NULL
);
""";
command.ExecuteNonQuery();
}
}The important statement is:
PRAGMA journal_mode = WAL;It enables WAL mode for the database.
Unlike several other SQLite settings, journal mode is persistent. Once WAL mode is successfully enabled, it remains associated with the database file across connections and application restarts unless another operation changes it.
For production applications, it is useful to verify the returned journal mode rather than assuming that the setting was applied successfully.
You can check it with:
PRAGMA journal_mode;The expected result is:
walWAL mode should normally be enabled during database initialization, not repeatedly changed while application operations are running.
Creating a Repository for Database Operations
After enabling WAL mode, create a repository that performs database operations.
The repository can open a new connection for each operation.
using Microsoft.Data.Sqlite;
public class TaskRepository
{
private readonly string _connectionString;
public TaskRepository(string connectionString)
{
_connectionString = connectionString;
}
public void AddTask(string title)
{
using var connection =
new SqliteConnection(_connectionString);
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = """
INSERT INTO Tasks
(Title, IsCompleted, CreatedAt)
VALUES
($title, 0, $createdAt);
""";
command.Parameters.AddWithValue(
"$title",
title
);
command.Parameters.AddWithValue(
"$createdAt",
DateTime.UtcNow.ToString("O")
);
command.ExecuteNonQuery();
}
public List<string> GetTasks()
{
var tasks = new List<string>();
using var connection =
new SqliteConnection(_connectionString);
connection.Open();
using var command = connection.CreateCommand();
command.CommandText = """
SELECT Title
FROM Tasks
ORDER BY Id DESC;
""";
using var reader = command.ExecuteReader();
while (reader.Read())
{
tasks.Add(reader.GetString(0));
}
return tasks;
}
}Each operation creates and disposes its own connection.
This is a reasonable starting point for a local application. SQLite connections are relatively lightweight, and Microsoft.Data.Sqlite supports connection pooling.
More importantly, the repository does not keep a connection open unnecessarily.
In a multi-process application, each process should establish its own database connections. Do not attempt to share a live SqliteConnection object between processes.
Understanding How WAL Improves Reader and Writer Concurrency
The main advantage of WAL mode is that readers and a writer can work concurrently in many situations.
For example, consider this sequence:
Process A starts reading records from the database.
Process B starts a write transaction.
Process B writes changes to the WAL file and commits.
Process A continues reading from its existing database snapshot.
A new read operation can see the committed changes.
The existing reader does not need to stop simply because another process committed a write.
This is possible because WAL mode uses snapshots. A reader continues seeing a consistent view of the database corresponding to its read transaction.
However, WAL mode does not provide unlimited write concurrency.
If Process A is writing while Process B attempts another write transaction, Process B may need to wait until the first writer finishes.
The following comparison summarizes the behavior:
Operation | Rollback-journal mode | WAL mode |
|---|---|---|
Multiple readers | Supported | Supported |
One writer | Supported | Supported |
Multiple simultaneous writers | Not supported | Not supported |
Reader during a write | May encounter blocking or locking | Usually allowed |
Write changes stored initially | Main database and journal | WAL file |
Checkpoint required | No WAL checkpoint | Yes |
For applications that perform many reads and relatively few writes, WAL mode can significantly improve the overall concurrency experience.
Handling Database Locking With Busy Timeouts
Even with WAL mode enabled, a process can receive a database-busy error when another process holds a conflicting lock.
For example, imagine two background services attempting to update the same database simultaneously.
If one service holds the write transaction for too long, the other service may have to wait.
SQLite provides a busy timeout that tells it how long to wait for a conflicting lock before returning an error.
With Microsoft.Data.Sqlite, you can configure the timeout through the connection string:
var connectionString =
new SqliteConnectionStringBuilder
{
DataSource = "app.db",
DefaultTimeout = 10
}.ToString();The timeout is expressed in seconds.
You can also configure SQLite's busy timeout explicitly:
PRAGMA busy_timeout = 10000;This sets a timeout of 10,000 milliseconds for the connection executing the statement.
A busy timeout does not make multiple writers run simultaneously. It simply allows a connection to wait for a conflicting lock to become available.
Choose a timeout based on the application's expected workload. A very long timeout can make an application appear unresponsive, while a very short timeout can cause unnecessary failures during normal activity.
Also, do not assume that every locking error has the same meaning. SQLITE_BUSY generally indicates that an operation cannot proceed because of a conflicting lock. SQLITE_LOCKED can indicate a different locking conflict, including certain conflicts within a connection or shared-cache configuration.
The application should log the actual SQLite error code and operation before deciding whether to retry.
Keeping Write Transactions Short
One of the most important WAL mode practices is to keep write transactions short.
Consider this example:
using var connection =
new SqliteConnection(connectionString);
connection.Open();
using var transaction = connection.BeginTransaction();
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText = """
UPDATE Tasks
SET IsCompleted = 1
WHERE Id = $id;
""";
command.Parameters.AddWithValue("$id", 10);
command.ExecuteNonQuery();
transaction.Commit();This transaction performs a small database update and commits immediately.
Avoid performing unrelated operations while holding a write transaction.
For example, the following workflow is not recommended:
Start transaction
|
v
Update database record
|
v
Call external API
|
v
Wait for response
|
v
Write application log
|
v
Commit transactionAn external API request can take several seconds or fail because of a network problem. Keeping the SQLite write transaction open during that time unnecessarily blocks other writers.
A better approach is to complete external operations before starting the database transaction whenever the business workflow permits it.
If an operation requires coordination between an external system and a database, design an explicit recovery or retry strategy rather than keeping a database transaction open while waiting for the external system.
Understanding WAL Checkpointing
WAL mode introduces another important concept: checkpointing.
As transactions commit, SQLite appends changes to the WAL file. These changes are eventually copied into the main database file.
This operation is called a checkpoint.
SQLite normally performs automatic checkpointing when the WAL file reaches a configured size threshold. The default automatic checkpoint threshold is generally 1,000 pages.
You can inspect the current checkpoint configuration:
PRAGMA wal_autocheckpoint;You can also request a checkpoint manually:
PRAGMA wal_checkpoint(PASSIVE);SQLite supports different checkpoint modes, including PASSIVE, FULL, RESTART, and TRUNCATE.
They have different locking and waiting behavior. PASSIVE attempts to checkpoint as much as possible without waiting for readers or writers. TRUNCATE attempts to complete the checkpoint and reduce the WAL file size to zero.
Do not run aggressive checkpoints after every database operation.
For many local applications, SQLite's automatic checkpointing is sufficient. Manual checkpointing is useful when the application has specific maintenance requirements or needs to monitor WAL growth.
Why the WAL File Can Become Large
A common production problem occurs when a process keeps a read transaction open for a long time.
For example:
Process A starts a read transaction.
Process B continues writing new records.
The WAL file grows as new changes are committed.
Process A continues using an older database snapshot.
SQLite cannot fully checkpoint changes that are still needed by the active reader.
As a result, checkpointing may not be able to reset or truncate the WAL file.
This is why applications should avoid keeping read transactions open while performing long-running calculations, external requests, or user interactions.
Read the required records, close the reader and transaction, and then perform additional processing outside the database operation whenever possible.
Choosing the Right Durability Setting
SQLite WAL mode also supports different synchronous settings.
For example:
PRAGMA synchronous = NORMAL;And:
PRAGMA synchronous = FULL;These settings control how aggressively SQLite synchronizes database changes to durable storage.
In WAL mode, NORMAL generally provides good performance while maintaining database consistency. However, recently committed transactions may be lost after a power failure or operating-system crash.
FULL provides stronger durability by synchronizing the WAL at each transaction commit, subject to the guarantees of the operating system and storage hardware.
The correct choice depends on how important the latest committed data is.
Setting | General behavior | Consideration |
|---|---|---|
NORMAL | Fewer synchronization operations | Better performance, with a durability trade-off after power loss |
FULL | Stronger synchronization at commit | Preferable when losing recently committed transactions is unacceptable |
Do not select NORMAL only to improve performance without understanding the application's recovery requirements.
Also remember that PRAGMA settings such as synchronous are connection-specific. If multiple processes create their own connections, configure the setting appropriately for each process.
Multi-Process SQLite Deployment Considerations
WAL mode has an important filesystem requirement.
The database, WAL file, and shared-memory file must be accessible through a filesystem that supports the locking and shared-memory behavior SQLite requires.
WAL mode is designed for processes running on the same host. It should not be used when multiple machines access the same database file over a network filesystem such as a typical network share.
The -shm file is used for shared-memory coordination. This is why simply placing a WAL database on a shared network drive does not make it a safe multi-machine database.
For multi-process applications running on the same machine, use a local filesystem and ensure that all processes have appropriate permissions to access the database and its associated files.
Also consider the following practices:
Keep the database file in a stable application data directory.
Avoid manually deleting the -wal or -shm files while processes are using the database.
Do not copy only the main database file while active WAL transactions may exist.
Use SQLite's backup facilities or a suitable consistent backup process.
Ensure that all processes use compatible SQLite versions and database settings.
Avoid long-running read transactions that prevent checkpoint progress.
These details become particularly important when a desktop application, Windows service, and command-line utility all use the same local database.
Monitoring WAL Growth and Database Health
A production application should monitor database behavior instead of assuming that WAL mode always solves concurrency problems.
Useful checks include:
PRAGMA journal_mode;
PRAGMA wal_autocheckpoint;
PRAGMA page_size;
PRAGMA page_count;You can also execute a checkpoint and inspect its result:
PRAGMA wal_checkpoint(PASSIVE);The checkpoint result provides information about whether the operation completed fully and how many WAL frames were checkpointed.
Monitor the following areas:
Database-busy errors and their frequency.
Time spent waiting for database operations.
Duration of write transactions.
WAL file size over time.
Checkpoint progress.
Application processes that keep connections or readers open.
If the WAL file grows continuously, investigate long-running readers and checkpoint behavior before trying to solve the problem by increasing the busy timeout.
Common Mistakes When Using WAL Mode
Assuming WAL Allows Multiple Writers
WAL improves reader and writer concurrency, but SQLite still permits only one active writer at a time.
Applications with frequent simultaneous writes should use a controlled write strategy.
Enabling WAL on Every Connection
Journal mode is persistent for the database. Enable it during database initialization and verify the result rather than repeatedly changing it during normal operations.
Keeping Transactions Open Too Long
Long-running transactions can increase lock contention and prevent checkpoints from completing.
Keep database transactions focused and short.
Deleting WAL Files Manually
The WAL and shared-memory files are part of SQLite's database operation.
Never delete them manually while database connections may still be active. Close the database cleanly and allow SQLite to manage its files.
Using WAL on a Network Share
WAL mode depends on shared-memory coordination and locking behavior that typical network filesystems do not provide safely.
Use a local filesystem for multi-process WAL access. For multiple machines, use a database server.
Ignoring Checkpoint Behavior
A growing WAL file can indicate long-running readers or incomplete checkpoint progress.
Monitor checkpoint behavior rather than assuming that the file will always remain small.
Summary
SQLite WAL mode is useful for .NET applications where multiple processes need to access the same local database file. It allows readers to continue using consistent database snapshots while a writer appends committed changes to the WAL file.
However, WAL mode does not support multiple simultaneous writers. Applications still need short transactions, appropriate busy timeouts, controlled write operations, and proper connection management.
Checkpointing is another important responsibility because committed changes in the WAL file must eventually be transferred to the main database. Long-running readers can delay this process and cause the WAL file to grow.
For applications running on the same machine, WAL mode can provide a practical improvement in database concurrency. Use a local filesystem, configure connection-specific settings correctly, monitor database behavior, and avoid manually modifying SQLite's internal files.
When an application needs many concurrent writers or access from multiple machines, a server-based database may be a better architectural choice. The goal is not simply to enable WAL mode, but to use SQLite in a way that matches the application's workload and reliability requirements.

Join the conversation! Your thoughts help the community grow.