GitHub Get synrag

synrag in production

Operations guide for platform and security teams: deployment, identity, access control, audit, encryption, monitoring, backup, scaling, connectors, and the security model with its limits.

0. Editions and licenses

Community (free, no license file)Licensed (file from Synlabs)
Search: BM25, Synapse, reranker; parsers; context with citationsyesyes
Collections, API keys, roles, metrics, live updates, journalyesyes
Sizeup to 1 000 000 chunks per organization (the binary counts per server)per license: Production 50M per installation, Enterprise unlimited
SSO tokens (sso), document ACLs (acl), audit log (audit), encryption at rest and rollback detection (encryption), cluster coordinator (cluster)—per license

--license-file acme.license (or SYNRAG_LICENSE_FILE); synrag license shows what is active, GET /license (role admin) too, with the chunks in use. The license is a signed file verified offline against keys built into the binary: no activation server, no network calls, no telemetry. Starting with an enterprise feature without a license is refused with a message naming the feature — security settings are never silently switched off. Above the chunk limit, writes get 402 Payment Required while searches, replacements and deletions keep working.

Expiry never locks data away. For 30 days after the expiry date everything keeps working (with a warning in the log). For the next 90 days the server serves searches with every feature it was using — access lists stay enforced, encrypted data stays readable, SSO and audit stay on — but refuses new documents. After that serve refuses to start until a renewed license file is installed. synrag export <collection.syn> -o docs.jsonl writes every document with its text and access list (the format POST /add takes) at any time, with or without a license (pass the encryption key as for any command). Deleting documents is always allowed. Without a license, a server also refuses collections that contain documents with access lists. Who may do what: LICENSE.md.

1. Deploy

Single node (Docker). The image is the binary on distroless (27 MB: glibc and CA certificates only, no shell, no package manager). An earlier musl / scratch image was 2.8 MB but built indexes ~55% slower (musl allocator).

docker build -t synrag:0.1.0 .
synrag keygen --id admin --roles admin            # prints the key once + its record
echo '{"keys":[<record>, ...]}' > secrets/keys.json
cp acme.license secrets/synrag.license                  # audit and encryption below are licensed features
synrag gen-encryption-key > secrets/key.hex       # optional: encryption at rest
docker run -p 7878:7878 -v $PWD/data:/data -v $PWD/secrets:/secrets:ro -v $PWD/models:/models:ro synrag:0.1.0 \
  serve --data /data --host 0.0.0.0 --api-keys /secrets/keys.json --encrypt-key-file /secrets/key.hex \
        --audit /data/audit.log --student /models/synapse.synm --license-file /secrets/synrag.license
# behind a reverse proxy, publish the port only to the proxy (e.g. -p 127.0.0.1:7878:7878) and add
#   --trust-proxy <proxy address or CIDR>   so the audit log records the real client address

Kubernetes (Helm). deploy/helm/synrag: one StatefulSet per shard (each pod a replica with its own volume), a stateless coordinator Deployment when shards > 1, Service, Ingress with TLS, probes (/ready, /health), non-root read-only containers, Secrets for keys / JWKS / encryption key, optional ServiceMonitor.

helm install kb deploy/helm/synrag --set shards=3,replicas=2,auth.jwt.enabled=true,ingress.enabled=true

TLS is terminated by the ingress controller, load balancer or service mesh (mTLS between pods with a mesh). synrag speaks plain HTTP inside the cluster and refuses to start without authentication on a non-loopback address (override: --insecure-no-auth).

2. Identity and roles

MechanismFlagsNotes
API keys--api-keys keys.jsononly SHA-256 of keys stored; constant-time check; per key: roles, ACL principals, allowed collections
SSO tokens (OIDC JWT)--jwks jwks.json (RS256) or --jwt-hs256-secret-file; --jwt-issuer, --jwt-audiencechecks signature, exp (required), nbf, iss, aud; 60 s leeway; verified tokens cached until expiry
Audience--jwt-audience is required with SSO tokens (or --jwt-any-audience)otherwise tokens issued for other applications would be accepted
Claims`--jwt-user-claim sub\oid\email, --jwt-groups-claim groups, --jwt-roles-claim roles, --jwt-default-roles read, --jwt-collections-claim`user → user:<claim>, each group → group:<name>

Identity providers: Keycloak, Entra ID (Azure AD: --jwt-user-claim oid, groups claim = group object ids), Okta, Auth0, Google (--jwt-user-claim email), ADFS. The JWKS file holds the provider's public keys; refresh it when the provider rotates keys (a CronJob that downloads .../.well-known/jwks.json into the Secret; synrag reads it at start — roll the pods after a rotation).

Roles: read (search, context), write (add, delete, upload, save; includes read), admin (collections and all of the above), metrics (/metrics), read-all (search ignoring document ACLs — compliance / e-discovery). admin does not imply read-all: managing collections does not grant access to restricted documents.

3. Collections (tenants)

--data <dir>: one <name>.syn (+ journal) per collection. POST /collections/{name} / DELETE (admin), GET /collections (lists only what the caller may use). Keys and tokens can be limited to collections, so one deployment can serve several departments or customers with hard separation.

4. Document-level access control

Each document may carry an ACL — the principals allowed to see it — set by connectors, by POST /add ("acl":["group:finance","user:alice"]), by uploads (?acl=), or at indexing (--acl, --acl-map prefix<TAB>principals). Documents without an ACL are visible to every reader of the collection, or to nobody with --acl-default deny.

The filter runs inside every retrieval channel before the top-k selection (BM25 accumulation and vector candidate lists), so restricted users get full result pages, and hidden documents are never scored into the candidate pool, packed into an LLM context, counted, or logged as returned. ACL entries are stored as 64-bit hashes plus a name table; a caller's principal matches only if the stored name is identical (no collision risk).

5. Audit

--audit audit.log: one JSON line per request — time, principal, client address (with --trust-proxy CIDR,... the X-Forwarded-For header is used, but only on connections from those proxies, and read from the right so a client cannot forge its address), request id, action, collection, query (--audit-queries full|hash|off), returned or changed documents, status, latency. Each record contains the SHA-256 of the previous record: synrag audit-verify audit.log detects removed, reordered or edited lines. Ship the file to the SIEM (Splunk, Elastic, Sentinel) and to WORM storage for retention. Authentication failures and 403s are recorded too.

External checkpoints. --audit-anchor <file on another volume | http://collector/path> with --anchor-key-file sends, every --audit-anchor-every records (1000), the sequence number and chain head with an HMAC. Someone able to rewrite the whole log (and recompute the chain) is still caught: synrag audit-verify audit.log --anchors checkpoints.jsonl --anchor-key-file k. Keep the key and the checkpoints off the data volume (KMS / Vault for the key, S3 Object Lock or the SIEM for the checkpoints).

6. Encryption at rest

--encrypt-key-file key.hex (or SYNRAG_ENCRYPT_KEY): index snapshots and every journal record are sealed with ChaCha20-Poly1305 (RFC 8439, tested against the RFC vectors); tampering or a wrong key is detected at load and the process refuses to start rather than truncating data. Keep the key in a KMS / Vault-backed Secret. Volume encryption (LUKS, EBS/KMS, CSI) is an alternative or an additional layer.

Key rotation. Snapshot all collections (POST /c/{name}/save), stop the server, run synrag rekey data/*.syn --old-key-file old.hex --new-key-file new.hex (refuses while a journal still has records), start with the new key. Each file is replaced atomically (written aside, then renamed); files already under the new key are skipped, so an interrupted rotation is completed by running the same command again.

Rollback detection. --state-anchor <file outside the data volume> with --anchor-key-file: per collection, the snapshot generation and journal length, HMAC-protected, updated and fsynced after every write and snapshot (--state-anchor-sync off trades that fsync for a window in which the last writes before a crash or rollback are not covered). At start, a collection older than its anchor — a restored backup, a rolled-back disk or volume snapshot — is refused until accepted explicitly (--accept-rollback name). The generation is authenticated only in encrypted snapshots: use it together with encryption at rest.

7. Durability, backup, restore

Every update is appended to the journal and fsynced before it is applied; on start the snapshot is loaded and the journal replayed (crash-tested with kill -9). A snapshot is written automatically when the journal reaches --snapshot-mb (default 256) and on POST /c/{name}/save. Backup = copy <name>.syn and <name>.syn.wal (volume snapshots work: both files are consistent at any instant). Restore = put them back and start.

Restoring a backup when a state anchor is used. The anchor is newer than any backup, so the server refuses the restored collection (by design: the same check catches a malicious rollback). Procedure:

  1. Stop the server. Keep the current anchor file (it records what the data looked like before the incident).
  2. Put the backup's <name>.syn and <name>.syn.wal in place.
  3. Start once with --accept-rollback <name> (comma-separated for several). The start is logged at level warn with the anchor's and the backup's generations, and the anchor is rewritten to the restored state.
  4. Start normally afterwards. Writes made after the backup are gone from that replica: in a cluster, repair it from a healthy replica instead (/cluster/repair merges by version), which needs no rollback at all.

7a. Upgrades and compatibility

7b. Write performance with every guarantee on

HTTP, BM25 only (no Synapse), laptop with NVMe, 1 200 single-document requests from 12 clients and 120 requests of 100 documents from 4 clients:

Configuration1 doc / request: p50 / p99, docs/s100 docs / request: docs/s
default (journal fsync per write)3.3 / 9.4 ms, 3 30069 000
--wal-sync off3.2 / 10.3 ms, 3 30081 000
fsync + audit + encryption at rest + state anchor (fsync)3.0 / 7.0 ms, 3 65049 000
coordinator + 2 replicas, write_ack: all, fsync on both3.0 / 8.9 ms, 3 40043 000

Repeated (5 full runs and 3 interleaved pairs of the previous and the current build, the same laptop on battery in power-saving mode, hence lower absolute numbers): medians 2 200–2 600 docs/s for single documents in every single-server mode — the differences between modes are smaller than the run-to-run spread (1 800–2 900), so the slightly better "all guarantees" figure above is noise; batches 37 000–41 000 (default), 32 000–36 000 (all guarantees, −10…−15 %; −29 % in the single run above), 27 000–29 000 (cluster). The cost of the guarantees depends on the disk and CPU — measure on the target hardware.

Single-document writes are serialised per collection (one journal); batch for bulk loads. Synapse embedding adds ~20 µs per document. Server disks differ: measure on the target hardware.

8. Monitoring and logs

GET /metrics (role metrics, or --metrics-public): request counts by route and status class, latency histograms, overload rejections, auth failures, connections, queue, documents added / deleted, snapshots, resident memory, per-collection chunks / documents / journal size. Logs: one JSON line per request on stderr (--log json|text|off). Health: /health (liveness), /ready (readiness; the server binds only after every collection is loaded).

9. Capacity and overload

A fixed pool of workers (--workers, default 4 × cores, 8–256) with a bounded queue (--queue, 1024): when it is full new connections get 503 + Retry-After instead of piling up. Persistent connections (keep-alive, idle --keepalive-s), request body limit (--max-body-mb, 64), header limits (32 KB, 100 headers), k ≤ 1000, context budget ≤ 200 000. A panic in one request closes that connection; the worker survives.

One node: 8.8 M short passages in 15–16 GB RAM (MS MARCO). Beyond one node: shards.

10. Scaling out (cluster)

synrag serve --cluster cluster.json runs a stateless coordinator in front of shard servers:

{"timeout_ms": 5000, "node_id": 0, "shards": [
  {"name": "s0", "replicas": ["synrag-s0-0:7878", "synrag-s0-1:7878"]},
  {"name": "s1", "replicas": ["synrag-s1-0:7878", "synrag-s1-1:7878"]}]}

Searches run in two phases like Elasticsearch's dfs_query_then_fetch: the coordinator sums the query terms' document frequencies over all shards, shards score BM25 with these collection-wide statistics, and the coordinator re-fuses the shards' hits with the union of their normalisation ranges (2 shards on FiQA: nDCG 0.2777 vs 0.2788 on one server). "global_idf": false skips phase one (−0.15 ms). Documents are partitioned by a hash of their source. Writes go to all replicas of the owning shard and succeed only when all applied them (idempotent: retry on failure). Reads fan out to one replica per shard in parallel with failover to the next replica, and results are merged by score; contexts are packed on the coordinator. The caller's credentials are passed through, so shards enforce the same roles and ACLs. Run two or more coordinators behind the Service. A replica that was down and missed writes (writes to its shard are refused while any replica is unreachable; the reachable ones may already have applied them) is brought back with one call: POST /cluster/repair?collection=kb&shard=s0&target=host:port (role admin) — the target pulls a snapshot from a healthy replica (/c/{col}/export → /c/{col}/import?from=). Tested on two machines: 29 MB in 2.6 s. Durability contract. A write answered with 200 is in the update journal of every replica that applied it, and — with the default --wal-sync on — fsynced to that replica's disk before the answer. So, per mode:

Event after a 200write_ack: allwrite_ack: available
process crash / kill -9 of any replicakept (journal replayed at start)kept
power loss of a replicakept (--wal-sync on); may lose the last writes with --wal-sync offsame
one replica's disk destroyedkept on the other replicas, repair copies it backkept only if another replica applied it; the answer lists replicas that did not (degraded)
all replicas of the shard destroyedlost (restore from backup)lost
journal record torn by a crash mid-writethat write was never acknowledgedsame

With write_ack: available, a write acknowledged by a single replica is as durable as that one disk until repair completes — use all (or ≥ 3 replicas) for data that must survive the loss of a disk.

Writes and consistency. The coordinator gives every write a version (milliseconds since 2025 × 4096 + counter, then 12 bits of node id): versions are strictly increasing on a coordinator and never equal across coordinators. "node_id" is required: a number 0..4095, distinct per coordinator, or "ordinal" to take the number the host name ends with (the Helm chart runs coordinators as a StatefulSet: pod …-coordinator-N gets N). With "service_key_file" set, a coordinator leases its id on every shard replica at start and renews the lease every 3 s (30 s validity); a second coordinator with the same id refuses to start ("node_id N is in use by another coordinator"), and a coordinator that lost its lease while cut off refuses writes (503) until it holds it again (tested). Without a service key the uniqueness is the operator's responsibility (a warning is logged). Each replica applies, per document source, only versions newer than the last one it applied — updates and deletes alike (a delete leaves a tombstone version, so a late older update cannot bring a document back). Concurrent writers through several coordinators therefore converge to the same state on every replica (last writer wins; clocks should be NTP-synchronised — within the clock skew the later version wins even if it was issued earlier). Retrying a write is safe. For strict per-document consistency use compare-and-set: "if_version": V on a document in /add (or on /delete) applies only if the source's current version is V (0 = does not exist yet); otherwise 409 with the current version, and nothing of the request is applied. Read → modify → write with if_version gives optimistic concurrency control like Elasticsearch's if_seq_no. Conditional writes are decided by the shard's primary (its first listed replica): the primary checks if_version under its write lock and assigns the new version; the other replicas receive the decided write. Of two writers expecting the same version exactly one succeeds, through any coordinators (tested: 20 rounds of two concurrent writers via two coordinators — always one 200 and one 409, replicas identical). If the primary cannot be reached, conditional writes fail with 503 rather than risk two successes in a partition; a 502 with "committed_on_primary": true means the write is decided and durable on the primary and other replicas get it by repair — re-read instead of retrying with the same if_version. Search hits carry each document's version for read → modify → write. With write_ack: available a write can be acknowledged without the primary (while it was unreachable), so the primary's copy may be older than what a client was told. The coordinator therefore first asks every other replica of the shard for the document's current version, and the primary checks if_version against the newest of all copies: a conditional write expecting the version from before a partition gets 409 with the newer version, and the primary is marked stale and merged (tested: primary cut off, ordinary writes on the other replica, primary back, conditional write with the old version → 409, the acknowledged write kept; with the new version → 200 on both replicas). If another replica does not answer, the conditional write fails with 503 (it might hold a newer acknowledged write). With write_ack: all no write is acknowledged without the primary, which decides alone. Of two writers expecting the same version exactly one succeeds in both modes (tested: 400 rounds through two coordinators, 200 per mode, repeated 5 times). An unconditional write is last-writer-wins: if it changes the same document at the same moment as a conditional write, the conditional write's guarantee does not cover it. Partitions. If the replicas of a shard were cut off from each other and each accepted writes (through different coordinators), repair merges instead of copying: each side takes from the other the documents whose version is newer (rebuilt with their ACLs) and the newer deletions; then both are identical (tested). What is kept is the newest version of every document: changes to different documents on the two sides all survive, but if both sides changed the same document, only the change with the later version remains (last writer wins) — the other one is overwritten, as with any LWW system. Where that is not acceptable, use conditional writes: during a partition they succeed only on the side that reaches the primary (and, with write_ack: available, every replica), so the two sides cannot both change a document conditionally. "write_ack": "all" (default): a write succeeds only when every replica of the shard applied it. "write_ack": "available": one replica per shard is enough; the others are marked stale (kept in "state_file"), are not read from, and are repaired automatically as soon as they answer again — the coordinator, with an admin key in "service_key_file", makes them pull a snapshot from an up-to-date peer. A replica holds its writes for the whole copy, so no write falls between the snapshot and the swap. Not yet: automatic resharding (choose the shard count up front; reindex to change it).

Transport between nodes. Coordinator ↔ shard and replica ↔ replica traffic carries credentials and document text. With replicas on other hosts, cluster.json must declare "transport": "mtls" (a service mesh — Linkerd, Istio with PeerAuthentication STRICT, which the Helm chart sets up with mesh: istio — or TLS sidecars such as ghostunnel / Envoy) or "transport": "plaintext" (isolated networks only); otherwise the coordinator refuses to start. The Helm chart adds a NetworkPolicy so that only synrag pods reach the shards. Tested across two machines through ghostunnel (TLS 1.3, client certificates): connections without a CA-issued client certificate, plaintext connections and direct connections to the shard port are refused; the coordinator keeps persistent connections, so the TLS handshake is paid once (p50 6 ms, p99 13 ms over Wi-Fi; TLS itself adds < 0.1 ms).

11. Connectors

python/synrag/connectors (standard library only): S3 and S3-compatible stores (SigV4), Confluence Cloud / Data Center (page restrictions → ACLs, inherited from ancestors), SharePoint Online / OneDrive (Microsoft Graph, item permissions → Entra ids), Google Drive (permissions → e-mails / domains; Docs exported), any SQL database (DB-API), local or mounted folders. sync() is incremental (versions in a state file), deletes what disappeared, retries transient errors with backoff. Schedule it as a CronJob. Scanned documents: --ocr-cmd "tesseract {} - -l rus+eng" at indexing.

12. Security model and limits