AiCredits
Schema design

Database Design for LLM Apps: Storing Conversations Efficiently

One row per message, token counts on the row, and background compaction: a practical schema that keeps your LLM chat history fast and cheap to replay.

Published 2026-12-03 Updated 2026-12-03 9 min

Why chat history tables rot

Almost every LLM app starts with the same table: id, conversation_id, role, content, created_at. It works fine until a user edits a message, regenerates an answer, or finance asks why last month's spend spiked. Then the table grows columns faster than the product grows features.

Three requirements should drive the schema instead. You need to rebuild the exact message array that was sent for any turn, attribute token spend to a single turn, and fetch a bounded context window with one indexed query. Get those right and editing, branching, and summarization all become variations on the same design.

The core schema: four tables, not one

Messages are rows, never a JSON blob. A blob kills per-message token accounting, turns concurrent appends into a lost-update race, and forces you to rewrite the whole document just to append one turn.

import sqlite3

DDL = """
CREATE TABLE IF NOT EXISTS conversations (
  id TEXT PRIMARY KEY,
  user_id TEXT NOT NULL,
  title TEXT,
  model TEXT NOT NULL DEFAULT 'deepseek-v4-flash',
  prompt_version TEXT,
  active_leaf_id TEXT,
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  updated_at TEXT NOT NULL DEFAULT (datetime('now')),
  deleted_at TEXT
);

CREATE TABLE IF NOT EXISTS messages (
  id TEXT PRIMARY KEY,
  conversation_id TEXT NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
  parent_id TEXT REFERENCES messages(id),
  seq INTEGER NOT NULL,
  role TEXT NOT NULL CHECK (role IN ('system','user','assistant','tool')),
  content TEXT NOT NULL,
  model TEXT,
  prompt_tokens INTEGER,
  completion_tokens INTEGER,
  cached_tokens INTEGER,
  finish_reason TEXT,
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
  deleted_at TEXT
);

CREATE UNIQUE INDEX IF NOT EXISTS ux_messages_conv_seq ON messages(conversation_id, seq);
CREATE INDEX IF NOT EXISTS ix_messages_parent ON messages(parent_id);
CREATE INDEX IF NOT EXISTS ix_conversations_user ON conversations(user_id, updated_at DESC);

CREATE TABLE IF NOT EXISTS conversation_summaries (
  conversation_id TEXT PRIMARY KEY REFERENCES conversations(id) ON DELETE CASCADE,
  covers_through_seq INTEGER NOT NULL,
  summary TEXT NOT NULL,
  model TEXT,
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);

CREATE TABLE IF NOT EXISTS request_snapshots (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  conversation_id TEXT NOT NULL REFERENCES conversations(id) ON DELETE CASCADE,
  message_id TEXT NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
  payload TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
"""

def connect(path="chat.db"):
    conn = sqlite3.connect(path)
    conn.row_factory = sqlite3.Row
    conn.execute("PRAGMA foreign_keys = ON")
    conn.executescript(DDL)
    conn.commit()
    return conn

seq is a per-conversation integer rather than a timestamp: two messages in the same turn can share a second, and ORDER BY created_at then returns them in arbitrary order. parent_id gives you a tree for free — any message with two children is a branch point. request_snapshots is the debugging escape hatch: sample one turn in a hundred and store the literal JSON payload you sent, so a bad answer can be reproduced without guessing which prompt template was live that day.

Record token usage on the row, not in logs

If usage only lives in your application logs, you cannot answer "which conversation is expensive" without an export job. The API returns usage on every response — write it into the assistant row in the same transaction. Store cached_tokens too; it is the only way to see whether your prompt layout is actually landing in the provider's prefix cache. The load_context helper used below is defined in the next section.

import os, uuid
from datetime import datetime, timezone
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["AICREDITS_API_KEY"],
    base_url="https://api.aicreditsapi.com/v1",
)

def now():
    return datetime.now(timezone.utc).isoformat(timespec="seconds")

def next_seq(conn, cid):
    return conn.execute(
        "SELECT COALESCE(MAX(seq), -1) + 1 FROM messages WHERE conversation_id = ?",
        (cid,),
    ).fetchone()[0]

def start_conversation(conn, user_id, system_prompt, model="deepseek-v4-flash", prompt_version="support-v3"):
    cid = uuid.uuid4().hex
    conn.execute(
        "INSERT INTO conversations (id, user_id, title, model, prompt_version) VALUES (?, ?, ?, ?, ?)",
        (cid, user_id, "New conversation", model, prompt_version),
    )
    conn.execute(
        "INSERT INTO messages (id, conversation_id, seq, role, content) VALUES (?, ?, 0, 'system', ?)",
        (uuid.uuid4().hex, cid, system_prompt),
    )
    conn.commit()
    return cid

def send_turn(conn, cid, user_text, budget_tokens=4000):
    user_msg_id = uuid.uuid4().hex
    conn.execute(
        "INSERT INTO messages (id, conversation_id, seq, role, content) VALUES (?, ?, ?, 'user', ?)",
        (user_msg_id, cid, next_seq(conn, cid), user_text),
    )
    conn.commit()

    history = load_context(conn, cid, budget_tokens)
    model = conn.execute("SELECT model FROM conversations WHERE id = ?", (cid,)).fetchone()["model"]
    resp = client.chat.completions.create(model=model, messages=history, temperature=0.3)

    usage = resp.usage
    details = getattr(usage, "prompt_tokens_details", None)
    cached = getattr(details, "cached_tokens", 0) or 0

    assistant_id = uuid.uuid4().hex
    conn.execute(
        """INSERT INTO messages
           (id, conversation_id, parent_id, seq, role, content, model,
            prompt_tokens, completion_tokens, cached_tokens, finish_reason)
           VALUES (?, ?, ?, ?, 'assistant', ?, ?, ?, ?, ?, ?)""",
        (assistant_id, cid, user_msg_id, next_seq(conn, cid), resp.choices[0].message.content,
         model, usage.prompt_tokens, usage.completion_tokens, cached, resp.choices[0].finish_reason),
    )
    conn.execute(
        "UPDATE conversations SET updated_at = ?, active_leaf_id = ? WHERE id = ?",
        (now(), assistant_id, cid),
    )
    conn.commit()
    return resp.choices[0].message.content

Assembling context in one query

The loader pins the system prompt, injects the rolling summary, then walks backwards from the newest message until the budget is spent. Persisted rows use their observed token counts; only the message you just inserted is estimated, and that estimate is replaced by the real count on the following turn.

def estimate_tokens(text):
    return max(1, len(text) // 4)

def load_context(conn, cid, budget_tokens):
    rows = conn.execute(
        """SELECT seq, role, content,
                  COALESCE(prompt_tokens, 0) + COALESCE(completion_tokens, 0) AS observed
           FROM messages
           WHERE conversation_id = ? AND deleted_at IS NULL
           ORDER BY seq""",
        (cid,),
    ).fetchall()

    context = [{"role": r["role"], "content": r["content"]} for r in rows if r["role"] == "system"]
    used = sum(estimate_tokens(m["content"]) for m in context)

    row = conn.execute(
        "SELECT summary, covers_through_seq FROM conversation_summaries WHERE conversation_id = ?",
        (cid,),
    ).fetchone()
    covered = row["covers_through_seq"] if row else -1
    if row:
        context.append({"role": "system", "content": "Summary of earlier turns:\n" + row["summary"]})
        used += estimate_tokens(row["summary"])

    picked = []
    tail = [r for r in rows if r["role"] != "system" and r["seq"] > covered]
    for r in reversed(tail):
        cost = r["observed"] or estimate_tokens(r["content"])
        if picked and used + cost > budget_tokens:
            break
        picked.append({"role": r["role"], "content": r["content"]})
        used += cost
    picked.reverse()
    return context + picked

Compaction belongs in a background job

Summarization should never run inside the user's request. Fold every N turns, in a worker, and write the result to conversation_summaries with the seq it covers. Raw messages stay on disk — you exclude them from context assembly by seq, not by deleting them, so you can still audit or re-summarize later when the summarizer improves.

deepseek-v4-flash handles this job well: it is fast and inexpensive enough to run over long transcripts routinely. Move the compaction job to deepseek-v4-pro when conversations are dense with code, figures, or decisions where a lossy summary costs more than the extra tokens.

def compact(conn, cid, keep_recent=6, max_chars=12000):
    prev = conn.execute(
        "SELECT summary, covers_through_seq FROM conversation_summaries WHERE conversation_id = ?",
        (cid,),
    ).fetchone()
    covered = prev["covers_through_seq"] if prev else -1

    rows = conn.execute(
        """SELECT seq, role, content FROM messages
           WHERE conversation_id = ? AND role != 'system' AND deleted_at IS NULL AND seq > ?
           ORDER BY seq""",
        (cid, covered),
    ).fetchall()
    if len(rows) <= keep_recent:
        return None

    to_fold = rows[:-keep_recent]
    transcript = "\n".join(f"{r['role']}: {r['content']}" for r in to_fold)
    if prev:
        transcript = "Existing summary:\n" + prev["summary"] + "\n\nNew turns:\n" + transcript

    resp = client.chat.completions.create(
        model="deepseek-v4-flash",
        temperature=0.2,
        messages=[
            {"role": "system", "content": "Compress the transcript into dense bullets. Keep names, numbers, decisions and open questions. No preamble."},
            {"role": "user", "content": transcript[:max_chars]},
        ],
    )
    summary = resp.choices[0].message.content

    conn.execute(
        """INSERT INTO conversation_summaries (conversation_id, covers_through_seq, summary, model)
           VALUES (?, ?, ?, ?)
           ON CONFLICT(conversation_id) DO UPDATE SET
             covers_through_seq = excluded.covers_through_seq,
             summary = excluded.summary,
             model = excluded.model,
             created_at = datetime('now')""",
        (cid, to_fold[-1]["seq"], summary, "deepseek-v4-flash"),
    )
    conn.commit()
    return summary

Indexes, pagination, and partitioning

One index does most of the work. Add the rest only when an actual query plan asks for them.

Query you will runIndexWhy it stays fast
Load the last N turnsux_messages_conv_seq (conversation_id, seq)Range scan plus ORDER BY in one pass, no sort step
Resume after compactionsame indexseq > covers_through_seq is still a range scan on the leading column
Conversation list per userix_conversations_user (user_id, updated_at DESC)Keyset pagination stays index-only
Branch / regeneration lookupix_messages_parent (parent_id)Cheap sibling lookup when a turn has two versions
Delete a user's historyFK cascade + monthly partitionsPartition drops beat million-row deletes

Paginate with keyset (WHERE updated_at < ? ORDER BY updated_at DESC LIMIT 50) rather than OFFSET, which degrades linearly with page depth. Once messages passes tens of millions of rows, partition by month on created_at: retention becomes a partition drop instead of a long DELETE, and recent conversations stay in a small hot set that fits comfortably in cache.

Branching without a second schema

  • Editing a user message: insert a new row with the same parent_id. Never UPDATE the old one.

  • Regenerating: insert a second assistant row with the same parent. The conversation now has two leaves.

  • Track the visible path with conversations.active_leaf_id and walk ancestors with a recursive CTE only when a branch actually exists.

  • Keep seq linear for the common case — the tree is metadata, not the read path.

  • Soft-delete with deleted_at so an undo does not require a restore job.

Prompt caching is a schema decision

Providers cache the longest matching prefix of your prompt, and cached input is billed at a lower rate than fresh input. That makes message order a cost decision, not a formatting preference. If your system message embeds a timestamp, or your loader interleaves the summary differently on every call, the prefix breaks and you pay full rate for the entire history on every turn.

Keep position 0 byte-identical (static system prompt), position 1 the summary, and everything after append-only. The load_context function above already behaves this way: the summary row only changes when compaction runs, so consecutive turns share a long cached prefix.

If two requests in the same conversation do not share a prefix, something in your loader is non-deterministic — fix that before you shorten the history.

AiCredits serves deepseek-v4-flash and deepseek-v4-pro behind one OpenAI-compatible endpoint at https://api.aicreditsapi.com/v1, payable by card or PayPal with no Chinese phone number or bank account required — so the client code above runs unchanged. Current rates, including off-peak and cache pricing, are listed at aicreditsapi.com/deepseek-prices.

FAQ

Should I store messages as JSONB or one row per message?

One row per message. JSONB is convenient for rendering, but it makes per-turn token attribution, concurrent appends, and partial loads awkward — you end up parsing the whole document to answer simple questions.

How much history should I keep verbatim?

Keep the most recent turns in full and summarize the rest. Tune the window by watching for answers that reference details which were folded away — that is the signal to raise the verbatim window or improve the summary prompt.

Do I need a vector database?

Only if you offer semantic search across old chats. Keep embeddings in a separate table keyed by message id, and never put a vector lookup on the hot path of context assembly.

How do I reproduce the exact prompt behind a bad answer?

Store model, prompt_version, and the rendered payload in request_snapshots for a sample of turns. Combined with parent_id, you can rebuild the rest of that branch deterministically.

Try Lint in 2 seconds

Wrote something? Paste it here for a free grammar check. No account needed.

More Tools →

Related Tools

💻Code Explainer

Was this article helpful?

| Share on X Reddit Copy link
💬
反馈意见 / Feedback ×