> ## Documentation Index
> Fetch the complete documentation index at: https://boutiquedb.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Concurrency & Thread Safety

> Master Swift concurrency isolation, DatabaseActor execution, transaction locks, and background writes in BoutiqueDB.

BoutiqueDB is architected around modern Swift concurrency (`async`/`await`, `@MainActor`, `Sendable`, and `Actor` isolation) to eliminate data races and `SQLITE_BUSY` crashes.

***

## Isolation Architecture

```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
flowchart TD
    UI[@MainActor UI Layer / SwiftUI] -->|async db.read / db.write| Actor[DatabaseActor Background Context]
    Actor -->|Isolated SQLite Handle| TursoEngine[(Turso C Engine / Storage)]
```

* **`BoutiqueDB` Container**: Annotated with `@MainActor`. You can store reference instances in your App State, `@StateObject`, or `@Observable` models.
* **`DatabaseActor`**: Isolated actor where all disk reads, SQL compilation, and writes take place.

***

## Read vs Write Isolation Rules

> [card] db.read Closure
>
> Provides a read-only `BoutiqueDBConnection`. Safe to run concurrent reads simultaneously across threads.

> [card] db.write Closure
>
> Provides an exclusive write transaction. Automatically manages `BEGIN` and `COMMIT`/`ROLLBACK`.

```swift ConcurrencyExample.swift theme={"theme":{"light":"github-light","dark":"github-dark"}}
// Execute write on background actor
try await db.write { conn in
    try Note.insert { newNote }.execute(conn.connection)
}

// Execute read on background actor
let notes = try await db.read { conn in
    try Note.all.fetchAll(conn.connection)
}
```

***

## Best Practices for Concurrency

> [!TIP]
>
> **Do**: Pass value-type models (`Sendable` structs) in and out of `db.read` and `db.write` closures.

> [!WARNING]
>
> **Don't**: Capture mutable state from outside the closure or call `@MainActor` methods from inside a `db.write` block. Doing so causes thread safety deadlocks.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.