Introducing a new way to review your PRs.

Read the announcement

karakeep-app / karakeep

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

View on GitHub

21 documents · Updated Nov 23, 2026

docs / data-model-and-persistence

Data model and persistence

Karakeep stores users, saved content, organization data, integrations, and background work in a local SQLite database. A shared Drizzle schema defines the domain model, while an ordered migration history moves each database to the current shape before application services use it. Authentication data follows the Better Auth account, session, and verification-token model.

Database lifecycle

The database lifecycle connects one durable SQLite file to the application services. Startup selects the file and its settings, then applies pending migrations before the web app and workers handle requests or background work.

Database initialization

The database uses the configured data directory when one is set. Otherwise it uses ./db.db; the application connection and migration tool use the same location through shared database configuration (packages/…/drizzle.config.ts• L1-18). The shared SQLite opener enables foreign-key checks and database performance settings. Writable connections use the configured journal mode and keep query-planner statistics fresh at open and once per day. Read-only connections require an existing file and accept queries only (packages/…/drizzle.ts• L8-22, packages/…/sqlite.ts• L3-66).

The local development launcher creates the data directory before it runs migrations. In the container image, the migration service runs before the web and worker services. A worker-only image assumes that this step was completed elsewhere. The migration entry point loads environment values before it reads shared configuration, then skips migrations in degraded mode. Degraded operation uses the existing database without writes (packages/…/migrate.ts• L1-14, packages/…/sqlite.ts• L12-36, start-dev.sh• L60-71, docker/root/etc/s6-overlay/s6-rc.d/init-db-migration/run#L1-L6, docker/Dockerfile#L175-L203).

References: packages/…/drizzle.config.ts• L1-18 packages/…/drizzle.ts• L8-22 packages/…/migrate.ts• L1-14 packages/…/sqlite.ts• L3-38 start-dev.sh• L60-71 docker/…/run• L1-6 docker/Dockerfile• L175-203

Migration history

Migrations are the durable record of schema change. Drizzle applies the ordered SQL files in packages/db/drizzle; new schema work starts by changing packages/…/schema.ts, then uses the database package's generate and migrate commands to create and apply a migration (packages/…/package.json• L8-16). The database package now also exposes type checking through its package script and inherits the shared Node TypeScript settings (packages/…/package.json• L8-11, packages/…/tsconfig.json• L1-8). The migration entry point loads environment configuration before it selects database settings and skips the apply step in degraded mode (packages/…/migrate.ts• L1-14, docs/…/03-database.md• L1-10).

The history shows that the model grows by preserving existing data. For example, list collaboration adds membership records and ties list membership rows to them, while import sessions add a staged path for bulk work (packages/…/0065_collaborative_lists.sql• L1-16, packages/…/0062_add_import_session.sql• L1-25). Later changes add fields or indexes without replacing the domain model, such as bookmark save-time ordering and reader-view assessment (packages/…/0092_add_last_saved_at.sql• L1-10, packages/…/0093_reader_view_assessment.sql• L1-4). The recent migrations add text anchors to highlights, then replace the asset and highlight user-only indexes with indexes that support ordered pagination (packages/…/0096_add_highlight_text_anchors.sql• L1-2, packages/…/0097_assets_highlights_pagination_indexes.sql• L1-4).

Migration 0097_assets_highlights_pagination_indexes is the latest ordered entry. Its generated snapshot describes the resulting SQLite schema for future migration comparisons, including highlight anchors and the new asset and highlight indexes (packages/…/_journal.json• L671-690, packages/…/0097_snapshot.json• L234-313, packages/…/0097_snapshot.json• L1494-1592).

References: packages/…/schema.ts• L1-17 packages/…/migrate.ts• L1-14 packages/…/package.json• L8-16 packages/…/tsconfig.json• L1-8 packages/…/_journal.json• L671-690 packages/…/0096_snapshot.json• L1490-1587 packages/…/0097_snapshot.json• L234-313 packages/…/0097_snapshot.json• L1494-1592 packages/…/0062_add_import_session.sql• L1-25 packages/…/0065_collaborative_lists.sql• L1-16 packages/…/0092_add_last_saved_at.sql• L1-10 packages/…/0093_reader_view_assessment.sql• L1-4 packages/…/0096_add_highlight_text_anchors.sql• L1-2 packages/…/0097_assets_highlights_pagination_indexes.sql• L1-4

Domain model

The domain model centers on a user-owned bookmark. Related records add the saved item's kind, captured content, organization, reading state, automation state, and external integration history without forcing every bookmark into one content shape.

Schema organization

The schema groups tables by the product concepts that use them. Core account and bookmark records come first, followed by content, organization, collaboration, automation, integration, billing, import, and backup records. Relation declarations then describe how those groups connect (packages/…/schema.ts• L44-1088, packages/…/schema.ts• L1090-1358).

The schema is the current model, while the migration directory is its change history. Runtime code imports the database and schema from the database package so API and worker flows use the same table names and relationship rules (packages/…/index.ts• L1-18).

References: packages/…/schema.ts• L44-1088 packages/…/schema.ts• L1090-1358 packages/…/index.ts• L1-18

User ownership

The user is the ownership boundary for most persistent data. Bookmarks, tags, lists, API keys, feeds, webhooks, rules, chat sessions, imports, backups, and subscription data point back to a user. Account removal can therefore remove dependent records through database cascade rules (packages/…/schema.ts• L44-125, packages/…/schema.ts• L127-211, packages/…/schema.ts• L213-234, packages/…/schema.ts• L684-829, packages/…/schema.ts• L836-960, packages/…/schema.ts• L962-1088).

Authentication records follow the same boundary through Better Auth accounts and sessions, while verification tokens support account verification without a user foreign key (packages/…/schema.ts• L127-211). User records also carry account timestamps and a boolean email-verification state. Legacy password and salt fields are removed by the Better Auth migration rather than kept beside the new credential-account record (packages/…/0094_migrate_to_better_auth.sql• L48-71, packages/…/0094_migrate_to_better_auth.sql• L103-123).

User settings persist product choices and service limits. They cover display behavior, reader preferences, AI behavior, backups, quotas, and subscription-related labels, so later flows can use the account record as their source of truth (packages/…/schema.ts• L44-125).

References: packages/…/schema.ts• L44-125 packages/…/schema.ts• L127-211 packages/…/schema.ts• L213-234 packages/…/schema.ts• L684-829 packages/…/schema.ts• L836-960 packages/…/schema.ts• L962-1088 packages/…/0094_migrate_to_better_auth.sql• L48-71 packages/…/0094_migrate_to_better_auth.sql• L103-123

Bookmark content

The bookmark is the stable record for a saved item. It stores common state such as title, archive and favorite flags, notes, source, timestamps, and the status of crawl and AI work. A type-specific record then stores link data, text data, or attached asset data (packages/…/schema.ts• L236-310, packages/…/schema.ts• L312-351, packages/…/schema.ts• L468-490).

Link data can hold fetched metadata and reader-ready content. File-like data is represented through assets, which belong to a user and can optionally belong to a bookmark. This lets the system persist images, documents, archives, videos, uploads, avatars, and backups as one asset family (packages/…/schema.ts• L353-407). Highlights and reading progress add user-specific reading state to a bookmark. A highlight also stores text before and after the selection as anchors for locating that selection again (packages/…/schema.ts• L409-466, packages/…/0096_add_highlight_text_anchors.sql• L1-2).

The bookmark's displayed creation time represents its most recent save. Its separate database creation time preserves when the row first appeared. This distinction lets re-saving affect ordering without losing the original creation point (packages/…/schema.ts• L236-253, packages/…/0092_add_last_saved_at.sql• L1-10).

References: packages/…/schema.ts• L236-351 packages/…/schema.ts• L353-407 packages/…/schema.ts• L409-490 packages/…/0092_add_last_saved_at.sql• L1-10 packages/…/0096_add_highlight_text_anchors.sql• L1-2

Bookmark organization

Tags and lists provide two different ways to organize bookmarks. Tags are user-owned labels connected through a many-to-many join record. Lists are user-owned collections that can be manual or query-based and can form a parent-child tree (packages/…/schema.ts• L492-572, packages/…/schema.ts• L574-662, packages/…/schema.ts• L1169-1234).

List sharing adds a membership record for each user-list pair and a separate invitation record for pending access. The bookmark-to-list link stores the membership that created it, so removing that membership also removes the associated list link (packages/…/schema.ts• L574-662, packages/…/0065_collaborative_lists.sql• L1-16).

References: packages/…/schema.ts• L492-662 packages/…/schema.ts• L1169-1234 packages/…/0065_collaborative_lists.sql• L1-16

Processing and integration records

Persistent records also describe work that changes or extends bookmarks. Import sessions track bulk imports and their staged bookmark rows. RSS feeds track source fetches and link entries to resulting bookmarks. Webhooks record user event subscriptions (packages/…/schema.ts• L725-800, packages/…/schema.ts• L962-1088).

Automation and AI use stored state rather than a separate copy of the bookmark. Rules point to user-owned tags or lists. Prompts store user choices. Bookmark status fields show whether crawl, tagging, summarization, or embedding work is pending, complete, or failed (packages/…/schema.ts• L262-270, packages/…/schema.ts• L664-702, packages/…/schema.ts• L836-901). The API and tRPC layer exposes these records to product flows, while background processing advances the stored work state. Chat sessions and messages form a user-owned conversation history for related AI features (packages/…/schema.ts• L684-723).

Backups persist a record of the saved backup asset and its result. Subscriptions persist the account's billing state, while invites and API keys persist access paths that remain bounded by user relationships (packages/…/schema.ts• L213-234, packages/…/schema.ts• L802-829, packages/…/schema.ts• L903-960).

References: packages/…/schema.ts• L213-234 packages/…/schema.ts• L262-270 packages/…/schema.ts• L664-829 packages/…/schema.ts• L836-901 packages/…/schema.ts• L903-960 packages/…/schema.ts• L962-1088

Persistence relationships

The relationships form a small set of durable paths through the product. A user owns the bookmark and its organization. The bookmark points to content and derived work. Integrations and background jobs add records that explain where the bookmark came from or what work remains.

Bookmark persistence path

This diagram shows how a saved item moves from its owner to its content variants and then to organization and user-specific reading records.

flowchart LR
    User[User] --> Bookmark[Bookmark]
    Bookmark --> Link[Link content]
    Bookmark --> Text[Text content]
    Bookmark --> AssetContent[Bookmark asset content]
    Bookmark --> StoredAsset[Stored asset]
    User --> Tag[Tag]
    Tag --> TagLink[Bookmark-tag link]
    Bookmark --> TagLink
    User --> List[List]
    List --> ListLink[Bookmark-list link]
    Bookmark --> ListLink
    User --> Reading[Reading state]
    Bookmark --> Reading

The type-specific content rows use the bookmark identifier as their link to the common bookmark. Tags and lists use join records because one bookmark can appear under many labels or collections. Reading progress and highlights also keep the user identifier because their state belongs to a reader rather than to the bookmark as a shared object (packages/…/schema.ts• L1092-1128, packages/…/schema.ts• L1130-1198, packages/…/schema.ts• L1346-1358). Highlight anchors remain part of that user-specific reading state and support stable selection context across content changes (packages/…/schema.ts• L419-457).

References: packages/…/schema.ts• L236-490 packages/…/schema.ts• L409-457 packages/…/schema.ts• L492-603 packages/…/schema.ts• L1092-1198 packages/…/schema.ts• L1346-1358

Import persistence path

The import model separates an import request from each staged item and from the final bookmark. This lets a bulk import report progress and keep an item-level result even when some items fail or duplicate existing data (packages/…/schema.ts• L962-1088).

flowchart LR
    Source[Import source] --> Session[Import session]
    Session --> Staged[Staged bookmark]
    Staged -->|accepted| Bookmark[Bookmark]
    Staged -->|rejected or duplicate| Result[Stored result]
    Session --> Root[List tree root]
    Bookmark --> SessionLink[Import bookmark link]
    Session --> SessionLink

The session belongs to a user and may point to a root list. Staged rows hold source data and processing state. The session-to-bookmark link records the durable result after creation (packages/…/schema.ts• L962-1088, packages/…/schema.ts• L1310-1333).

References: packages/…/schema.ts• L962-1088 packages/…/schema.ts• L1310-1333

Deletion behavior

Foreign-key actions define what happens when an owner or parent record is removed. Dependent user data and most child bookmark data use cascade deletion. Optional links use set-null when the history should remain without the deleted parent, such as an RSS import's bookmark or an import session's root list (packages/…/schema.ts• L127-211, packages/…/schema.ts• L312-407, packages/…/schema.ts• L773-800, packages/…/schema.ts• L962-1088).

Collaborative list data follows the same rule at membership level. A list link can be tied to a membership, which prevents an old membership from leaving access-related list content behind (packages/…/schema.ts• L574-662).

References: packages/…/schema.ts• L127-211 packages/…/schema.ts• L312-407 packages/…/schema.ts• L574-662 packages/…/schema.ts• L773-800 packages/…/schema.ts• L962-1088

Change checklist

When these files or sections are changed, remember to consider these:

  • A schema change in packages/…/schema.ts must have a matching ordered migration in packages/db/drizzle so existing installations can reach the new shape.
  • A change to a foreign key or delete action must be checked against the related join records. This includes bookmark tags, bookmark lists, list memberships, imports, RSS entries, and assets.
  • A change to bookmark time fields must preserve the API meaning of the displayed save time and the separate first-created time.
  • A change to status fields must remain compatible with the workers and any API flow that reads pending or failed work.
  • A change to the database file location must affect both runtime connection setup and migration configuration.
  • A change to degraded-mode behavior must keep the read-only database connection and migration skip behavior aligned.
  • A change to SQLite connection settings must preserve foreign-key checks, the selected journal mode, and query-only behavior for degraded mode.
  • A change to query-planner maintenance must keep optimization bounded and non-fatal so a maintenance error does not stop database startup or later work.
  • A change to migration startup configuration must load environment values before shared configuration reads the data directory or degraded-mode setting.
  • A change to import or backup records must preserve the link between progress state and the stored bookmark or asset result.
  • A change to authentication tables must preserve Better Auth's account-provider uniqueness, user links, session tokens, verification-token uniqueness, and the migration path from legacy credentials.
  • A change to the database package's TypeScript settings or scripts must keep database code type-checkable and keep migration generation and application commands available to the workspace.
  • A change to highlight text or anchor fields must preserve the link between the selected text, its offsets, and the surrounding text used to find it again.
  • A change to asset or highlight pagination must keep the index order aligned with the user filter, sort fields, and stable identifier tie-breaker used by the page query.

Important failure modes

TriggerConsequenceGuard
The service starts without applying the current migration historyRuntime queries can target columns or tables that do not existRun the migration service before web and worker services (docker/root/etc/s6-overlay/s6-rc.d/init-db-migration/run#L1-L6, docker/Dockerfile#L175-L203)
Degraded mode points to a missing database fileThe read-only connection fails instead of creating a databaseStart degraded operation only with an existing database file (packages/…/sqlite.ts• L12-20)
SQLite planner maintenance fails during connection setup or its daily runDatabase use could be interrupted by a non-essential optimization taskKeep optimization errors logged as warnings and separate from normal database access (packages/…/sqlite.ts• L40-65)
A schema change is made without a migrationExisting databases remain on the old shapeGenerate and apply a Drizzle migration for every schema change (packages/…/package.json• L8-12, docs/…/03-database.md• L1-6)
A parent record is deleted with the wrong foreign-key actionChild data can disappear unexpectedly or leave an invalid relationshipReview cascade and set-null behavior in the affected relationship (packages/…/schema.ts• L574-662, packages/…/schema.ts• L773-800)
A bookmark save-time change updates only one timestamp meaningSorting can change while the API loses the original creation pointKeep last-save and first-create semantics aligned (packages/…/schema.ts• L236-253, packages/…/0092_add_last_saved_at.sql• L5-10)
Import staging and result links are changed out of syncA bulk import can report progress without a reliable final bookmark resultPreserve the session, staged row, and result bookmark relationships (packages/…/schema.ts• L1010-1088)
Better Auth migration data is copied without its ownership or uniqueness rulesExisting users can lose sign-in paths or new sign-ins can collidePreserve account-provider uniqueness, valid user links, and the legacy credential conversion (packages/…/0094_migrate_to_better_auth.sql• L1-75, packages/…/schema.ts• L127-186)
Database package scripts or inherited TypeScript settings drift from workspace expectationsDevelopers can lose the standard migration or type-check path, or database changes can pass without the intended type checksKeep typecheck, generate, and migrate scripts aligned with the shared Node TypeScript configuration (packages/…/package.json• L8-16, packages/…/tsconfig.json• L1-8)
The highlight anchor migration is missing or only partly appliedSaved highlights can lose the context needed to locate their selected textApply migrations 0096 and 0097 in order and keep the schema snapshot current (packages/…/0096_add_highlight_text_anchors.sql• L1-2, packages/…/_journal.json• L671-690)
Asset or highlight pagination uses an index that does not match its user and sort fieldsPages can require broad scans or return unstable page boundaries as data changesKeep the composite indexes and their query order aligned (packages/…/0097_assets_highlights_pagination_indexes.sql• L1-4, packages/…/schema.ts• L402-416, packages/…/schema.ts• L447-456)

Key files

FileWhy to read it
packages/…/schema.tsDefines the current domain model, authentication records, ownership boundaries, status fields, foreign-key actions, relations, highlight anchors, and pagination indexes.
packages/…/drizzle.tsShows how the application database connection uses the shared SQLite opener and schema.
packages/…/sqlite.tsDefines the shared writable and read-only SQLite connection behavior.
packages/…/drizzle.config.tsDefines the shared database file location and migration output.
packages/…/migrate.tsShows the migration entry point, environment loading order, and degraded-mode behavior.
packages/…/package.jsonDefines database migration, generation, and type-check commands.
packages/…/tsconfig.jsonShows the shared Node TypeScript configuration used by the database package.
packages/…/_journal.jsonRecords the ordered migration history known to the database tool, including migrations 0096 and 0097.
packages/…/0097_snapshot.jsonRecords the current schema snapshot, including highlight anchors and the asset and highlight pagination indexes.
packages/…/0097_assets_highlights_pagination_indexes.sqlShows the index changes that support asset and highlight pagination.
packages/…/0096_add_highlight_text_anchors.sqlShows the migration that adds surrounding text anchors to highlights.
packages/…/0094_migrate_to_better_auth.sqlShows how legacy OAuth and password records move to the Better Auth account model.
packages/…/0062_add_import_session.sqlIllustrates the durable import session and staged-work model.
packages/…/0065_collaborative_lists.sqlIllustrates list sharing and membership-linked bookmark relationships.
packages/…/0092_add_last_saved_at.sqlIllustrates a data-preserving change to bookmark ordering semantics.
docker/root/etc/s6-overlay/s6-rc.d/init-db-migration/runShows the container startup step that applies migrations before services run.
docs/…/03-database.mdGives the short developer workflow for generating and applying migrations.