SQLite is a lightweight database engine that works particularly well for applications that need local storage without running a separate database server. It is commonly used in desktop applications, command-line tools, background services, and applications that need to work offline.
As an application grows, multiple components may access the same SQLite database. A background worker may save records while the user interface reads them. A scheduled task may update data while another process performs a backup. Several application instances may also open the same database file.
These situations can introduce database locking problems. Developers may encounter errors such as database is locked or database is busy, even when the SQL statements themselves are correct.
SQLite supports concurrent database access, but it does not allow multiple write transactions to modify the same database simultaneously. Applications must understand this behavior and manage database connections, transactions, and timeouts carefully.
This article explains why SQLite database locks occur, how Microsoft.Data.Sqlite handles busy conditions, and how to build reliable database operations in .NET applications.
Understanding SQLite Database Locking
SQLite uses locks to coordinate access between database connections. These locks prevent multiple operations from making incompatible changes to the same database file.
Unlike a traditional database server that can manage multiple concurrent writers internally, SQLite allows only one active write transaction at a time.
This does not mean that only one application connection can be open. Several connections can read the database, and they can request write operations. However, write transactions must take turns.
Consider an application with two independent database connections:
Connection A starts a transaction and updates a record.
Connection B attempts to update another record.
Connection B must wait until Connection A completes its transaction.
If Connection A holds the transaction for too long, Connection B may receive a busy or locked error.
The problem is not necessarily that SQLite is unavailable. Another connection may simply be holding a lock that the current operation needs.
Common Reasons for Database Lock Errors
Understanding the cause of a lock is more useful than increasing the timeout immediately.
Long-Running Transactions
A transaction should contain only the database operations that need to succeed or fail together.
Consider this example:
using var transaction = connection.BeginTransaction();
UpdateCustomer(connection, transaction);
CallExternalService();
SaveOrder(connection, transaction);
transaction.Commit();
The transaction remains active while the application communicates with an external service. If the service takes several seconds to respond, the database write transaction remains open for that entire period.
Other connections may have to wait before they can write.
A better approach is to perform external operations before opening the database transaction whenever possible.
var externalResult = CallExternalService();
using var transaction = connection.BeginTransaction();
UpdateCustomer(connection, transaction);
SaveOrder(
connection,
transaction,
externalResult);
transaction.Commit();
This keeps the transaction focused on database work and reduces the time for which the write lock is held.
Multiple Application Instances
A desktop application may allow users to open several instances. Each instance may create its own SQLite connections and perform background operations.
For example, one instance may save user preferences while another instance updates cached records. Both processes are accessing the same database file.
SQLite coordinates these operations through file locking, but the application must still handle situations where one process cannot obtain the lock immediately.
Background Workers
Background workers are another common source of contention.
An application may have a synchronization service that periodically downloads information and saves it to SQLite. At the same time, the user interface may allow users to update the same records.
If the background worker processes a large batch inside one transaction, other components may experience delays.
The solution is not always to reduce the number of connections. Instead, the application should keep write transactions short and avoid unnecessary database operations.
Long-Running Read Transactions
Read transactions can also affect write operations, depending on the journal mode.
In the traditional rollback journal mode, readers can prevent a writer from completing certain stages of its transaction.
In WAL mode, readers and a writer can generally operate concurrently. However, long-running readers can prevent checkpoints from fully advancing because SQLite must preserve database pages that are still needed by existing read snapshots.
Therefore, even read operations should not keep transactions open longer than necessary.
Configuring Busy Timeouts in Microsoft.Data.Sqlite
When a database is temporarily locked, an application does not always need to fail immediately. It can wait for the current transaction to complete.
Microsoft.Data.Sqlite automatically retries many busy and locked operations until the command timeout is reached.
The default command timeout is 30 seconds. Applications can configure a different value according to their requirements.
For example:
using Microsoft.Data.Sqlite;
using var connection =
new SqliteConnection("Data Source=app.db");
connection.DefaultTimeout = 60;
connection.Open();
DefaultTimeout controls the timeout used by commands created through the connection, including certain implicit commands created internally by Microsoft.Data.Sqlite.
A specific command can also have its own timeout:
using var command = connection.CreateCommand();
command.CommandText =
"""
UPDATE Tasks
SET IsCompleted = 1
WHERE Id = $id;
""";
command.Parameters.AddWithValue("$id", 10);
command.CommandTimeout = 60;
command.ExecuteNonQuery();
A longer timeout can help when the application occasionally encounters short periods of write contention.
However, increasing the timeout does not fix a transaction that remains open indefinitely. It only allows the application to wait longer.
For an interactive application, waiting 60 seconds for a database operation may be worse than returning a clear message and allowing the user to try again. Choose a timeout based on the expected operation and user experience.
Understanding Busy and Locked Errors
SQLite provides different error codes for database access problems.
Two commonly encountered primary result codes are:
Error code | Name | General meaning |
|---|
5 | SQLITE_BUSY | Another database connection or process is preventing the operation from proceeding |
6 | SQLITE_LOCKED | A conflicting lock exists, often involving the same connection or shared-cache table locking |
The exact cause should be investigated rather than treating both errors as identical.
Microsoft.Data.Sqlite exposes SQLite error information through SqliteException.
try
{
command.ExecuteNonQuery();
}
catch (SqliteException ex)
{
Console.WriteLine(
$"SQLite error: {ex.SqliteErrorCode}");
Console.WriteLine(
$"Extended error: {ex.SqliteExtendedErrorCode}");
throw;
}
The primary error code identifies the broad category, while the extended error code can provide more detail.
For example, SQLITE_BUSY_SNAPSHOT can occur when a transaction tries to upgrade an older read snapshot into a write transaction after another connection has already committed a change.
This distinction matters because retrying only the failed SQL statement may not be sufficient. The complete transaction may need to be rolled back and started again.
Using WAL Mode to Improve Concurrency
Write-Ahead Logging is one of the most useful SQLite features for applications with frequent reads and occasional writes.
In the traditional rollback journal mode, database changes are eventually written directly into the main database file. Locking can prevent readers from accessing the database during certain stages of a write operation.
In WAL mode, changes are first written to a separate write-ahead log file. Readers can continue accessing an earlier consistent database snapshot while a writer appends changes to the WAL file.
Enable WAL mode with:
PRAGMA journal_mode=WAL;
In a .NET application, the setting can be configured during database initialization:
using var connection =
new SqliteConnection("Data Source=app.db");
connection.Open();
using var command = connection.CreateCommand();
command.CommandText =
"PRAGMA journal_mode=WAL;";
string? mode =
command.ExecuteScalar()?.ToString();
if (!string.Equals(
mode,
"wal",
StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
"Could not enable SQLite WAL mode.");
}
WAL mode is especially useful when the application performs frequent reads while background operations update records.
However, it does not allow multiple simultaneous writers. SQLite still serializes write transactions.
WAL also creates additional files alongside the database, including the WAL and shared-memory files while the database is active. These files are part of normal operation and should not be deleted manually while connections are using the database.
WAL is not suitable for every storage environment. In particular, applications should avoid assuming that it will work safely on network file systems that do not provide the required shared-memory and locking behavior.
Keeping Transactions Short
The most effective way to reduce lock contention is to minimize the time spent inside write transactions.
Consider an application that imports several records from an external source. A poor implementation might download the data, parse it, validate it, and then save everything while holding a database transaction.
A better implementation separates preparation from persistence.
public async Task ImportTasksAsync(
CancellationToken cancellationToken)
{
var downloadedTasks =
await DownloadTasksAsync(cancellationToken);
var validTasks =
downloadedTasks
.Where(task => !string.IsNullOrWhiteSpace(task.Title))
.ToList();
using var connection =
new SqliteConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
using var transaction =
connection.BeginTransaction();
foreach (var task in validTasks)
{
using var command = connection.CreateCommand();
command.Transaction = transaction;
command.CommandText =
"""
INSERT INTO Tasks (Title, IsCompleted)
VALUES ($title, 0);
""";
command.Parameters.AddWithValue(
"$title",
task.Title);
command.ExecuteNonQuery();
}
transaction.Commit();
}
The network request and validation happen before the transaction begins. The transaction contains only the database inserts.
For very large imports, consider processing records in batches. Smaller transactions can reduce lock duration, although the application must decide whether partial batch completion is acceptable.
If the entire import must succeed or fail as one unit, splitting it into separate committed transactions changes the business behavior and should not be done without considering the consequences.
Choosing Deferred and Immediate Transactions
Microsoft.Data.Sqlite supports deferred transactions.
A deferred transaction delays acquiring the actual database transaction until the first database statement is executed.
using var transaction =
connection.BeginTransaction(deferred: true);
This can be useful when a transaction starts with read operations and may later perform a write.
However, a deferred transaction can encounter a problem when it tries to upgrade from a read transaction to a write transaction while another connection has changed the database.
In WAL mode, this can result in SQLITE_BUSY_SNAPSHOT. The transaction's original read snapshot is no longer the latest database state, so SQLite cannot safely promote it to a writer.
When an operation is known to require a write transaction, an immediate transaction can acquire the write reservation earlier:
using var transaction =
connection.BeginTransaction(deferred: false);
This makes contention visible at the beginning of the operation instead of after several statements have already executed.
There is a trade-off. An immediate transaction reserves the writer position earlier, which can reduce concurrency if the transaction performs unnecessary work before committing.
Choose the transaction type according to the operation:
Transaction type | Suitable scenario | Consideration |
|---|
Deferred | Operations that may only read | Can fail when upgrading to a writer |
Immediate | Operations known to require writes | Acquires write access earlier |
Default transaction behavior | Simple database operations | Understand the provider's transaction defaults |
Do not use immediate transactions for every operation without considering their effect on other writers.
Handling Transient Lock Errors With Controlled Retries
Microsoft.Data.Sqlite already retries many busy and locked operations until the configured timeout is reached. An application should not add another retry loop around every SQL statement.
There are situations where the application must retry the complete transaction. One example is a transaction that fails during a read-to-write upgrade.
A retry should follow a controlled process:
Roll back or dispose of the failed transaction.
Wait for a short period.
Start a new transaction.
Repeat the complete operation.
Stop after a limited number of attempts.
The following example demonstrates a bounded retry approach for an operation that can safely be executed again:
using Microsoft.Data.Sqlite;
public static async Task ExecuteWithRetryAsync(
Func<Task> operation,
int maxAttempts = 3,
CancellationToken cancellationToken = default)
{
for (int attempt = 1; ; attempt++)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
await operation();
return;
}
catch (SqliteException ex)
when (ex.SqliteErrorCode == 5 &&
attempt < maxAttempts)
{
int delayMilliseconds =
100 * attempt;
await Task.Delay(
delayMilliseconds,
cancellationToken);
}
}
}
This helper demonstrates the retry policy, but the operation passed to it must manage its own transaction. Each attempt should create a new connection or use a connection in a clean state, start a new transaction, and roll back on failure.
The operation must also be safe to repeat. For example, an insert that creates duplicate records on every retry is not automatically safe. Use unique constraints, idempotency keys, or an appropriate upsert strategy where necessary.
Do not retry every SQLite exception. A syntax error, missing table, invalid column, or constraint violation is not a temporary locking problem. Retrying such errors only delays the actual failure.
Avoiding Shared Connection Usage Across Threads
SQLite supports concurrent access through separate connections, but Microsoft.Data.Sqlite connection objects are not thread-safe.
Do not share one SqliteConnection, SqliteCommand, or SqliteDataReader across threads that use them concurrently.
Instead, create a separate connection for each independent database operation:
public sealed class TaskRepository
{
private readonly string _connectionString;
public TaskRepository(string connectionString)
{
_connectionString = connectionString;
}
public async Task<int> GetTaskCountAsync(
CancellationToken cancellationToken)
{
await using var connection =
new SqliteConnection(_connectionString);
await connection.OpenAsync(cancellationToken);
await using var command =
connection.CreateCommand();
command.CommandText =
"SELECT COUNT(*) FROM Tasks;";
object? result =
await command.ExecuteScalarAsync(
cancellationToken);
return Convert.ToInt32(result);
}
}
Connection pooling makes opening and closing logical connections more efficient. It is generally preferable to creating one shared connection and trying to coordinate access to it from multiple threads.
This approach does not eliminate SQLite write contention. It ensures that application code uses the provider safely while SQLite manages access to the underlying database.
Common Mistakes to Avoid
One common mistake is increasing the busy timeout without investigating long-running transactions. A longer timeout may make the application appear to work while users experience unnecessary delays.
Another mistake is retrying only the final SQL statement after a transaction has failed. When a transaction has become invalid or its snapshot is outdated, the application should roll back and repeat the complete unit of work.
Developers should also avoid assuming that WAL mode supports multiple concurrent writers. It improves reader and writer concurrency, but write transactions still execute one at a time.
Finally, do not hold a database transaction open while waiting for user input, calling an external API, processing a large file, or performing unrelated calculations. These activities increase lock duration and make contention more likely.
Best Practices for Production Applications
A reliable SQLite implementation should follow a few consistent practices:
Keep write transactions short and focused.
Use WAL mode when the application's access pattern benefits from concurrent readers and a writer.
Configure command timeouts according to the expected workload.
Use a separate connection for each independent operation.
Inspect SQLite primary and extended error codes when diagnosing failures.
Retry only errors that are genuinely transient.
Roll back and retry the complete transaction when a transaction cannot safely continue.
Make retried operations idempotent.
Monitor transaction duration and database busy errors.
Avoid using SQLite on storage environments that do not provide reliable locking and shared-memory behavior.
For applications with sustained high write concurrency, a server-based database may be a better fit. SQLite is excellent for local storage and many embedded workloads, but its single-writer design should be considered when planning the application's architecture.
Summary
SQLite database locks are a normal part of its concurrency model. Multiple connections can access the same database, but only one write transaction can be active at a time. Long-running transactions, background workers, multiple application instances, and read-to-write transaction upgrades can all produce busy or locked errors.
Microsoft.Data.Sqlite provides automatic retries for many busy and locked conditions, along with configurable command timeouts. WAL mode can improve concurrency between readers and a writer, while short transactions reduce the time other operations must wait.
The most reliable solution is to combine sensible connection management, focused transactions, appropriate timeouts, and carefully controlled retries. Developers should investigate the reason for a lock rather than simply increasing the timeout. This approach helps SQLite-based .NET applications remain responsive and reliable as their workloads grow.
SQLiteMicrosoft.Data.Sqlite.NETdatabase lockingbusy timeouttransactionsWAL mode
Join the conversation! Your thoughts help the community grow.