mqlite logomqlite

A message queue in a single SQLite file.

Peek-Lock delivery, retries, dead-letter queues, scheduling, dedup, FIFO groups and topic fan-out — embedded in your Go process or served as a tiny HTTP broker. Same engine, same file, your choice.

Latest release v0.4.3 pure Go · no CGO one binary · one file JSON over HTTP · curl-able local SQLite or remote Turso MIT

# what it solves

Three problems that keep re-appearing in every backend.

“I need background jobs, not a broker deployment.”

A cluster to operate, an SDK to learn, a bill to pay — for one service.
→ a library over one file

Zero infrastructure. Want HTTP later? The same engine runs as one ~30 MB process.

“My DB write and my event can disagree.”

Save the order, publish the event — crash in between and they split. Outbox tables and CDC are yet more machinery.
→ one transaction for both

The queue is your SQLite DB: business write + enqueue commit atomically.

“My hand-rolled jobs table became a bad broker.”

A status column and a polling loop slowly regrow locks, retries, dead-letters — untested.
→ these semantics come finished

Peek-Lock, retries → DLQ + redrive, FIFO groups, delays, dedup — pinned by a conformance suite.

# why mqlite

Design priorities, in order — when they conflict, the earlier one wins.

1Lightweight & embeddable

One pure-Go binary over one SQLite file. No broker cluster, no sidecar, no CGO. Start embedded; move the same code to a broker, or the storage to replicated Turso, without rewriting your app.

2Reliable under concurrency

Default Peek-Lock delivery is honestly at-least-once; explicit receive-and-delete chooses at-most-once broker removal. New settlements require a current token and unexpired lease; send deduplication when configured, bounded receive/settlement replay, single-broker crash recovery, and O(log n) claims on a deep backlog. FIFO groups stay ordered even across consumer crashes and lock expiry.

3Simple, unambiguous interface

Every operation is one HTTP POST with a JSON body — 29 routes, curl-able by construction, exactly one settlement verb per outcome (Complete / Abandon / Reject / Defer), no aliases. Easy for people; easy for agents.

4Service Bus flavor, not a clone

Peek-Lock, group_id sessions, DLQ + redrive, scheduling and duplicate detection feel familiar from Azure Service Bus — in an idiomatic-Go shape, with the whole model documented and its public compatibility invariants pinned by a conformance suite.

# the killer feature: a transactional outbox with no outbox

Because the queue is your SQLite database, a business write and its event commit in one transaction. Creating the order and its initial queue event succeeds or rolls back together — no dual-write race, no CDC pipeline, no poller.

Embedded-only: this shape avoids a separate broker or Postgres dependency. External brokers can't join your SQLite transaction, and Postgres-based queues need a Postgres. Here the business data and queue share one file.
package main

import (
    "context"
    "log"

    "github.com/mqlitehq/mqlite"
    "github.com/mqlitehq/mqlite/engine"
)

func main() {
    ctx := context.Background()
    mq, err := mqlite.OpenEmbedded(ctx, "file:./app.db")
    if err != nil {
        log.Fatal(err)
    }
    defer mq.Close()
    if err := mq.CreateQueue(ctx, "order-events", mqlite.QueueConfig{}); err != nil {
        log.Fatal(err)
    }

    err = mq.Tx(ctx, func(tx *engine.EngineTx) error {
        // Demo schema; application migrations normally create this table.
        if _, err := tx.SQL().ExecContext(tx.Context(),
            `CREATE TABLE IF NOT EXISTS orders(id INTEGER PRIMARY KEY, total INTEGER NOT NULL)`); err != nil {
            return err
        }
        // 1) the business write, on the SAME transaction. Use tx.Context(), not the
        //    ctx you passed to Tx — a statement interrupted mid-transaction wedges
        //    a local SQLite database.
        if _, err := tx.SQL().ExecContext(tx.Context(),
            `INSERT INTO orders(id, total) VALUES(?, ?)`,
            42, 1999); err != nil {
            return err // rollback: nothing enqueued
        }
        // 2) enqueue — commits atomically with it:
        _, err := tx.SendOne("order-events",
            engine.OutMessage{Body: []byte(`{"order":42}`)})
        return err
    })
    if err != nil {
        log.Fatal(err)
    }
    // A nil result confirms that the order and its event committed together.
}

The snippet starts with a fresh app.db and inserts order 42 once. Atomicity keeps the business write and enqueue together; it does not make external side effects exactly-once or prove that a timed-out remote commit failed. Reconcile an uncertain outcome before retrying. See transactional enqueue.

# how it works

Two delivery targets, one storage story: a topic stores nothing — the thing that stores, is consumed, and can dead-letter is always a queue.

animated contract · 9 seconds

one publish · two independent deliveries

step 1 / 8
01 · publish

The publisher sends order.created to the implicit events topic.

  1. 01 · publishThe publisher sends order.created to the implicit events topic.
  2. 02 · routeThe topic stores nothing. Both subscription filters match this message.
  3. 03 · copyaudit and fulfillment each receive an independent backing-queue copy: same message ID, different sequence numbers.
  4. 04 · claimEach Receive changes its copy from active to locked and increments delivery_count to 1.
  5. 05 · settle differentlyaudit completes, so only its message copy is removed; the subscription remains. Below the delivery limit, fulfillment abandons with delay, moving its copy locked → scheduled without incrementing the count.
  6. 06 · dueThe scheduler returns the delayed copy to active. Its delivery count is still 1.
  7. 07 · retryThe next Receive locks the copy and increments delivery_count to 2.
  8. 08 · completeThe retry completes, so that message copy is removed too; both subscriptions remain. Delivery is at-least-once, so handlers must remain idempotent.

Animation timing is illustrative, not broker latency. A final ordinary claim may still renew and complete at the delivery limit. It enters the DLQ if explicitly rejected, or if that final lock is abandoned, expires, or is explicitly reclaimed. See shutdown and restart boundaries.

the source version described here is covered by the conformance TCK — details in Concepts; the full construction story (schema, locks, fencing, recovery) is in Internals

# the honest part

Published historical measurements from specific workloads; remeasure the current release with your payloads, concurrency and monitoring enabled before sizing production. Methods and limits: docs/benchmark.md. Historical Turso environment and comparison: PR #67.

SetupMeasuredRead this as
Local file DB, 12-core machine 15,926–17,963 msg/s single · 35,146 batched historical local results; rerun the workload before sizing
1-vCPU / 256 MB cloud box, embedded engine 6.0–6.7k msg/s batched batching amortized commit cost in this measured setup
Remote Turso (co-located) ~45 ms p50 per single durable send historical co-located run; remote commit latency dominated this path
Memory / disk 27–34 MB peak RSS · freed DB pages are reusable file reclamation is gradual; size disk for peak backlog and measure your workload

when NOT to use mqlite — it is a single-writer, single-node queue by design

If you need…Use instead
Log streaming, replay, consumer groups over historyKafka · Redpanda · NATS JetStream
A clustered, highly-available multi-node brokerNATS · RabbitMQ
A queue inside the Postgres you already runpgmq · River
Sustained six-figure msg/s on one nodenot this — the single-writer model is the point, not a bug
Exactly-once external side effectsdefault Peek-Lock delivery is at-least-once; make handlers idempotent

# deeper references

The boundaries, evidence and executable contract behind the overview — rendered from the same source Markdown so people and machines read the same facts in either language.

# quickstart

Three ways in — they all drive the same engine. These installation examples use the latest published modules and image; verify the installed version and use its matching release documentation; see Deployment for installation and runtime settings.

Writing a broker-only Go application? The official MQLite Remote Client for Go (mqlite-go) is standard-library-only and keeps a Go 1.13 source floor: go get github.com/mqlitehq/mqlite-go@latest. Use the full SDK below for embedded queues, transactional outbox, observation, or managed access-key administration.

No server at all: one import, one file — the queue lives inside your process. go get github.com/mqlitehq/mqlite@latest (documented source floor: Go ≥ 1.21; check the installed release's go.mod).

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/mqlitehq/mqlite"
)

func main() {
    ctx := context.Background()
    mq, err := mqlite.OpenEmbedded(ctx, "file:./mq.db")
    if err != nil {
        log.Fatal(err)
    }
    defer mq.Close()

    if err := mq.CreateQueue(ctx, "orders", mqlite.QueueConfig{
        LockDuration:     30 * time.Second,
        MaxDeliveryCount: 5,
    }); err != nil {
        log.Fatal(err)
    }

    // produce
    if _, err := mq.SendOne(ctx, "orders", mqlite.OutMessage{Body: []byte(`{"id":42}`)}); err != nil {
        log.Fatal(err)
    }

    // consume (Peek-Lock): receive, do work, then settle
    msgs, err := mq.Receive(ctx, "orders", mqlite.RecvOpts{Max: 10, Wait: 5 * time.Second})
    if err != nil {
        log.Fatal(err)
    }
    for _, m := range msgs {
        fmt.Printf("got: %s\n", m.Body)
        // Abandon retries below max (DLQ at max); Reject sends directly to DLQ.
        if err := m.Complete(ctx); err != nil {
            log.Fatal(err)
        }
    }
}

One tiny process, secure by default: it generates a mqk_… token and prints it if you don't set one. Every operation is one POST.

go install github.com/mqlitehq/mqlite/cmd/mqlite@latest   # latest published broker

# start the broker on :6754 with a known token, in the background
MQLITE_TOKENS=mqk_dev MQLITE_DB=file:./mq.db mqlite serve --addr :6754 &
export TOKEN=mqk_dev        # (omit MQLITE_TOKENS to have the broker generate + print one)

# create a queue, send, receive — curl-able by construction
curl -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
     --data '{"name":"orders","config":{}}' \
     localhost:6754/mqlite.v1.AdminService/CreateQueue

curl -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
     --data "{\"queue\":\"orders\",\"messages\":[{\"body\":\"$(printf hi | base64)\"}]}" \
     localhost:6754/mqlite.v1.QueueService/Send

curl -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \
     --data '{"queue":"orders","max_messages":1,"wait_time_ms":5000}' \
     localhost:6754/mqlite.v1.QueueService/Receive

A named volume keeps queue data across container replacement. The admin console is available at /ui; opening the root URL in a browser enters that console while curl and JSON clients keep the discovery card. The console groups subscriptions by topic and shows permanent or fixed lifetimes against the broker clock; its five-second loop calls only Observe, while lifecycle inventory refreshes on connection, explicit refresh and configuration changes.

This example follows the latest published image. Pin a verified tag or digest for reproducible deployments. For production configuration and recovery, follow Deployment and the operations runbook.

docker run -d --name mqlite -p 127.0.0.1:6754:6754 \
  -e MQLITE_TOKENS=mqk_dev \
  -e MQLITE_DB=file:/data/mq.db \
  -v mqdata:/data \
  ghcr.io/mqlitehq/mqlite:latest serve --addr :6754

curl http://localhost:6754/          # discovery card (no auth)
# opening that root URL in a browser enters the admin console

# one key for each application

Keep a configured administrator token and issue separate application keys at runtime, with no broker restart.

Permissions apply across one broker. Tokens are shown once; the database stores only their digests. Manage keys through the Go SDK, HTTP API, CLI, console or MCP.

Read the access key guide →

# run it in production

Start with one broker over a persistent local SQLite file. Choose a durability setting and rehearse recovery before putting messages into production.

Prometheus collection is off by default. Enable --metrics or MQLITE_METRICS=on to serve authenticated /metrics on the API port, and give the collector a separate MQLITE_MONITOR_TOKENS credential. Keep collection on a private network; if the API has public ingress, deny /metrics there. Use mqlite_queue_retained_messages and mqlite_queue_oldest_message_age_seconds. The starter includes Prometheus, Grafana, a dashboard and verification scenarios.

# built for AI agents too

The API was shaped so a model can drive it without tripping: one POST per operation, one verb per outcome, a machine-readable discovery card at GET /, an MCP server (mqlite-mcp, 22 tools in the documented source), and llms.txt / llms-full.txt for anything that reads the web. Copy-paste prompts and setup: For AI agents →