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

> ## Agent Instructions
> Magpie is a trace store for AI agents, used as a library (crate `magpiedb`, npm `magpiedb`, PyPI `magpiedb`) or as `magpie-server`, which takes OpenTelemetry (OTLP over HTTP on 127.0.0.1:4318 and gRPC on 127.0.0.1:4317 by default).
> Use only the commands, flags, routes and JSON shapes that these pages show. Do not guess a flag or a query field: if a page does not show it, say that the docs do not show it.
> Packages and server binaries are not published yet: build from source, as the quick start shows. Check the status note on the introduction page before you suggest `cargo add`, `npm install` or `pip install`.
> Only one process may write to a store folder at a time. For many apps, send traces to one `magpie-server`.

# magpie-server

> Install, run and configure magpie-server: every command-line flag, Docker, a full disk, retention, host names, slow clients and the limits of the server.

`magpie-server` is one process that takes OpenTelemetry traces over OTLP and writes them to one Magpie store, or to one store per tenant (see [Tenants](https://docs.magpiedb.com/reference/tenants-and-keys.md#tenants)). It also serves a JSON query API. API keys decide who may read and write which tenant (see [API keys](https://docs.magpiedb.com/reference/tenants-and-keys.md#api-keys)), and both ports can use TLS (see [TLS](https://docs.magpiedb.com/reference/tenants-and-keys.md#tls)). The one store can also be kept in an S3 bucket, and other servers can answer queries from the bucket (see [S3](https://docs.magpiedb.com/reference/server-s3.md)).

Why: a store has one writer. When many app instances send traces, this server is that one writer.

New here? Start with the [quickstart](https://docs.magpiedb.com/quickstart.md). To choose between the library and the server, read [Library or server](https://docs.magpiedb.com/library-or-server.md). How to send from an app or a framework: [OpenTelemetry guide](https://docs.magpiedb.com/guides/opentelemetry.md). This reference covers every flag. The routes are in the [HTTP API](https://docs.magpiedb.com/reference/http-api.md) reference.

## Run it

```sh theme={null}
cargo build --release -p magpie-server
target/release/magpie-server --dir ./traces                       # one store, no keys, local connections only
target/release/magpie-server keygen --tenant acme --rights read,write >> keys.jsonl   # shows the key once
target/release/magpie-server --tenants-dir ./tenants --auth keys --keys-file keys.jsonl --tls-cert cert.pem --tls-key key.pem --http-addr 0.0.0.0:4318 --grpc-addr 0.0.0.0:4317
target/release/magpie-server --dir ./traces --s3 s3://my-bucket/traces                # the writer: the store is also in the bucket
target/release/magpie-server --s3 s3://my-bucket/traces --read-only --cache-dir ./cache --http-addr 127.0.0.1:4320 --grpc-addr 127.0.0.1:4319   # queries from the bucket
```

| flag | default | meaning |
| - | - | - |
| `--dir` | (one of the two) | The store directory. Made if it does not exist. |
| `--tenants-dir` | (one of the two) | One store per tenant, in `<dir>/<tenant id>`. See [Tenants](https://docs.magpiedb.com/reference/tenants-and-keys.md#tenants). |
| `--max-open-tenants` | `100` | Tenants: stores open at once. |
| `--tenant-idle-secs` | `300` | Tenants: a store that no request used for this long is closed. |
| `--http-addr` | `127.0.0.1:4318` | OTLP/HTTP (`POST /v1/traces`) and the query API. An IP address and a port (a host name is not looked up). |
| `--grpc-addr` | `127.0.0.1:4317` | OTLP/gRPC. An IP address and a port. |
| `--durability` | `disk` | What an accepted export survives. `disk`: a machine crash. `os`: a crash of the server process. `none`: nothing after the last commit. |
| `--min-free-mb` | 5% of the volume, at least `16`, at most `1024` | The free space that every store keeps on its volume: under it, new spans and scores are refused. `0`: no reserve. See [A full disk](https://docs.magpiedb.com/reference/server.md#a-full-disk). |
| `--retention` | (keep everything) | Keep spans this long, in every store: a whole number and `s`, `m`, `h` or `d` (`30d`, `12h`). See [Retention](https://docs.magpiedb.com/reference/server.md#retention). |
| `--prices` | (no cost is computed) | A price table file (JSON). The cost of a model call that comes with tokens and no cost is computed from it. See [Cost](https://docs.magpiedb.com/reference/mapping-cost-masking.md#cost). |
| `--mask` | (nothing is masked) | A mask policy file (JSON). Private data is replaced in every span and score before it is stored. See [Masking](https://docs.magpiedb.com/reference/mapping-cost-masking.md#masking). |
| `--pieces` | off | Keep a repeated piece of a long text once (a pointer), in every store. A store opens with either value. |
| `--max-body-bytes` | `67108864` | The largest request body, before and after gzip decoding: 64 MiB, the default that the OTLP spec recommends. An SDK's full batch (512 spans) of model calls of 50 KB each is about 26 MB. Larger: `413` (gRPC: `RESOURCE_EXHAUSTED`, also for a message on the wire; OTLP clients do not send it again). See [Limits](https://docs.magpiedb.com/reference/server.md#limits). |
| `--allowed-host` | (none) | Answer requests sent to this host name too (`Host`, gRPC `:authority`); give it again for more. With no keys on a loopback address the server answers only to `localhost` and IP addresses; with no keys this flag turns that check on for any address. With keys there is no check. See [Host names](https://docs.magpiedb.com/reference/server.md#host-names). |
| `--ingest-memory-mb` | `512` | What the decodes of the writes in flight may take at once (counted from the bytes before the decode: protobuf by its schema, JSON by every value in it; not below the real decode in any shape measured). A request that alone would take more: `413 DECODE_TOO_LARGE` (gRPC `RESOURCE_EXHAUSTED`); the others wait for it. See [Limits](https://docs.magpiedb.com/reference/server.md#limits). |
| `--max-list-items` | `10000` | The most items of one list of a request, counted before the decode: OTLP attributes (of a span, the resource, the scope, an event, a link), events and links of a span, values of an array or a kvlist (also nested), resources, scopes; a JSON array of the query API, the words of a `words` text, the scores of one write (in OTLP/JSON only the spans of a scope are not counted). A protobuf field of one message that comes twice: `400`. More: `413 LIST_TOO_LONG` (gRPC `RESOURCE_EXHAUSTED`). The spans of a scope have their own cap. See [Limits](https://docs.magpiedb.com/reference/server.md#limits). |
| `--max-spans-per-request` | `100000` | OTLP: the most spans in one request. More: `413` (gRPC `RESOURCE_EXHAUSTED`), counted before the decode (protobuf and JSON). See [Limits](https://docs.magpiedb.com/reference/server.md#limits). |
| `--header-timeout` | `30s` | HTTP: the headers of a request must arrive in this time (`ms`, `s`, `m`, `h` or `d`); an idle keep-alive connection is closed after it; a gRPC connection must send its first request in it. See [Slow clients](https://docs.magpiedb.com/reference/server.md#slow-clients). |
| `--body-timeout` | `60s` | A request body must arrive in this time once it is read: else `BODY_TIMEOUT` and the connection closes (OTLP: `503` with `Retry-After`; other routes: `408`). gRPC: the whole export (wait, body, write), else `DEADLINE_EXCEEDED`. See [Slow clients](https://docs.magpiedb.com/reference/server.md#slow-clients). |
| `--max-connections` | `1024` | Connections at a time, on each port (TLS handshakes count). The next one waits in the system's queue until one closes. |
| `--grpc-max-connection-age` | `10m` | A gRPC connection is asked to close after this time (GOAWAY: the requests in progress end); clients open a new one. See [Slow clients](https://docs.magpiedb.com/reference/server.md#slow-clients). |
| `--max-mapped-bytes` | 2 x `--max-body-bytes` (128 MiB) | OTLP: the most bytes of one request's spans, each with a copy of its resource and scope. More: `413` (gRPC `RESOURCE_EXHAUSTED`), before any copy is made. See [Limits](https://docs.magpiedb.com/reference/server.md#limits). |
| `--auth` | (none) | `keys`: every request needs an API key (`--keys-file`). `trusted-header`: tenants only, `x-magpie-tenant` is trusted. With `--tenants-dir`, one of the two is required. See [API keys](https://docs.magpiedb.com/reference/tenants-and-keys.md#api-keys). |
| `--keys-file` | | The key file, with `--auth keys`. |
| `--tls-cert`, `--tls-key` | (none) | TLS on both ports: the certificate chain (PEM, the server's certificate first) and its private key (PEM). When the server's own certificate (the first) is not valid now, the server does not start; when it ends soon, or another certificate of the file is not valid, a warning. See [TLS](https://docs.magpiedb.com/reference/tenants-and-keys.md#tls). |
| `--no-ui` | (the viewer is on) | Do not serve the read-only web viewer at `/` and `/ui/*`. See [Viewer](https://docs.magpiedb.com/reference/viewer.md). |
| `--s3` | (local disk only) | `s3://<bucket>/<prefix>`: the store is kept in a bucket. With `--dir`: this server is the writer. With `--read-only`: it answers queries from the bucket. Not with `--tenants-dir`. See [S3](https://docs.magpiedb.com/reference/server-s3.md). |
| `--s3-endpoint` | `AWS_ENDPOINT_URL`, or AWS | Another S3 service, for example a MinIO: `http://127.0.0.1:9000`. |
| `--s3-upload-interval` | `10s` | Writer: at most one upload per this time (`ms`, `s`, `m`, `h` or `d`). At most half of `--s3-lease`. |
| `--s3-lease` | `60s` | Writer: a new writer does not start while the newest manifest in the bucket is younger than the lease of the writer that made it. |
| `--s3-take-over` | (off) | Writer: start although another writer may hold the store. That writer then stops accepting writes. |
| `--s3-gc-grace` | `30m` | Writer: an object that the store no longer needs is deleted after this time. |
| `--s3-gc-interval` | `10m` | Writer: how often old objects are deleted. |
| `--read-only`, `--cache-dir` | | With `--s3` and no `--dir`: a read-only server on the bucket, with its block cache in this folder. |
| `--cache-mb` | `1024` | Read-only: the most megabytes in `--cache-dir`. |
| `--cache-block-kb` | `256` | Read-only: the bucket is read in blocks of this size. |
| `--s3-refresh` | `5s` | Read-only: how often the server looks for a newer manifest. At most half of the writer's `--s3-gc-grace`. |

`magpie-server --version` prints the build, the store format it reads and writes, and the version of the GenAI mapping: `magpie-server 0.1.0 (store format 14, GenAI mapping v2)`. `--help` prints every flag. A wrong flag prints its reason and one line that points to `--help`, with exit code 2.

New spans are searchable after the next commit. The store commits 0.5 s after the first write that waits for a commit (`Options::commit_interval` in magpiedb), and the commit itself takes time (with `--durability disk`, a full flush of the disk) before a query sees it. So a span is found no sooner than about 0.5 s after its `200`, and later on a busy machine: how much later depends on the machine, not on a setting (`tests/searchable.rs` counts it; F90).
SIGINT or SIGTERM stops both listeners, waits for requests in progress, and closes the store (a final commit). A slow client cannot hold that wait for long: its request ends at `--header-timeout` or `--body-timeout` (an export to a slow reader still has no limit, see [Limits](https://docs.magpiedb.com/reference/server.md#limits)).

The default addresses accept local connections only. To accept traces from other machines (`--http-addr 0.0.0.0:4318`), use API keys and TLS, or a private network.

## Environment variables

For S3, the server reads the usual AWS variables. See [S3](https://docs.magpiedb.com/reference/server-s3.md).

## Send traces to it

Any OpenTelemetry SDK, with the standard environment variables:

```sh theme={null}
OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf   # or http/json
OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4317 OTEL_EXPORTER_OTLP_PROTOCOL=grpc
# with API keys and TLS: the key in a header (%20 is the space), and the CA that signed the server's certificate
OTEL_EXPORTER_OTLP_ENDPOINT=https://magpie-host:4318 OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer%20mgp_..." OTEL_EXPORTER_OTLP_CERTIFICATE=ca.pem
```

An OpenTelemetry Collector, as one more exporter:

```yaml theme={null}
exporters:
  otlphttp/magpie:
    endpoint: https://magpie-host:4318    # the exporter adds /v1/traces
    headers: { authorization: "Bearer ${env:MAGPIE_KEY}" }
    tls: { ca_file: ca.pem }              # not needed for a certificate of a public CA
  otlp/magpie:                            # or gRPC
    endpoint: magpie-host:4317
    headers: { authorization: "Bearer ${env:MAGPIE_KEY}" }
    tls: { ca_file: ca.pem }              # without TLS on the server: tls: { insecure: true }
service:
  pipelines:
    traces:
      exporters: [otlphttp/magpie]
```

What is tested: the OpenTelemetry JS exporters for protobuf, JSON and gRPC, with an API key and TLS from the environment variables above (`e2e/`), and Rust clients (`tests/server.rs`, `tests/auth.rs`). A Collector binary was not tested; it speaks the same protocol.

For the setups of agent frameworks (Vercel AI SDK, LangChain and LangGraph, OpenAI Agents SDK, Mastra), see the [OpenTelemetry guide](https://docs.magpiedb.com/guides/opentelemetry.md).&#x20;

How the server reads the OTLP bodies is in [HTTP API](https://docs.magpiedb.com/reference/http-api.md#otlp-behavior). How it maps spans is in [Mapping, cost and masking](https://docs.magpiedb.com/reference/mapping-cost-masking.md).

## Docker

From release 0.1.0 on, every release has an image for amd64 and arm64: `ghcr.io/intojhanurag/magpie-server:<version>`, and `latest` for the newest release. Release 0.1.0 is not out yet. The `Dockerfile` in the repo root builds the same image from the sources:

```sh theme={null}
docker run --rm -p 127.0.0.1:4318:4318 -p 127.0.0.1:4317:4317 -v magpie-data:/data ghcr.io/intojhanurag/magpie-server:0.1.0
docker build -t magpie-server .     # or: from the sources of this repo (some minutes), then `docker run ... magpie-server`
```

The image is Debian 13 slim with the server and `ca-certificates` (for `--s3` on an `https` endpoint), nothing else. The server runs as uid and gid 10001 (named `magpie`), not root. The image gives them as numbers, so Kubernetes with `runAsNonRoot: true` accepts it. A bind mount instead of a volume must be writable by uid 10001; in Kubernetes, give a new volume `securityContext: {fsGroup: 10001}` in the pod. The health check (`magpie-healthcheck`, every 30 s) asks `GET /healthz` on the HTTP port; it reads the server's `--http-addr` and `--tls-cert`, so it follows another port and TLS. The released image takes the binary of the release archive (`--build-arg BINARY=release`, `.github/workflows/server-release.yml`): it runs the same bytes as the download.

The store is in the volume `/data`. In the container the server listens on `0.0.0.0` (else the published ports cannot reach it); `-p 127.0.0.1:...` keeps it on this machine. To accept traces from other machines, add API keys and TLS (`docker run ... magpie-server --auth keys --keys-file /data/keys.jsonl --tls-cert ... --tls-key ...`: arguments after the image name are added to the server's). With no keys the image's host check is on (section [Host names](https://docs.magpiedb.com/reference/server.md#host-names)): `localhost` and IP addresses pass, a service name must be given with `--allowed-host`. With keys there is no host check.

Compose, with no keys (an app in the same file sends to the service name `magpie`):

```yaml theme={null}
services:
  magpie:
    image: ghcr.io/intojhanurag/magpie-server:0.1.0   # or: build: . (from this repo)
    command: ["--allowed-host", "magpie"]   # added to the image's own flags
    ports: ["127.0.0.1:4318:4318", "127.0.0.1:4317:4317"]
    volumes: ["magpie-data:/data"]
  app:
    environment:
      OTEL_EXPORTER_OTLP_ENDPOINT: http://magpie:4318
volumes:
  magpie-data:
```

Kubernetes, with no keys (a Service `magpie` in the namespace `observability`; the probe sends the pod's IP, which passes):

```yaml theme={null}
containers:
  - name: magpie
    image: ghcr.io/intojhanurag/magpie-server:0.1.0
    args: ["--allowed-host", "magpie", "--allowed-host", "magpie.observability",
           "--allowed-host", "magpie.observability.svc.cluster.local"]
    ports: [{containerPort: 4318}, {containerPort: 4317}]
    readinessProbe:
      httpGet: {path: /healthz, port: 4318}
```

On a network that other people reach, use `--auth keys` and TLS instead. These two files were not run here (no Docker or Kubernetes on the test machine); the host rule they need is tested on the binary (`tests/hardening.rs`, `an_ip_address_passes_the_host_check_and_keys_turn_it_off`). The image runs as a user without rights, and stops cleanly on `docker stop` (SIGTERM: the store is closed).

## A full disk

What the server does when the volume of its store gets full, and what to do then.

* **It refuses new data before the disk is full.** Every store keeps a reserve of free space on its volume: `--min-free-mb`, by default 5% of the volume, at least 16 MiB and at most 1 GiB. A write of spans or scores is refused with `503` (gRPC `UNAVAILABLE`) and a text that starts with `io: DISK_FULL:` while the volume has less free space than the reserve plus the room that the accepted spans still need for their commit. Nothing of a refused request is stored. OTLP clients send it again.
* **Everything else goes on:** queries, `POST /v1/traces/delete`, `POST /v1/purge`, `--retention`, commits, and a restart. The reserve is the room for them. A merge in the background starts only when there is room for its output too; while one runs on a nearly full volume, new data can be refused until it ends.
* **How to make room.** Free space on the volume (a bigger volume, other files). Or drop old data: `--retention` drops whole old files with no rewrite, so it is the cheap way. Or delete traces and then purge: the purge writes the files that hold deleted spans again, so it needs room for the spans that stay in them (delete the oldest traces: their files go whole). A purge that has no room fails with its own error and changes nothing.
* **It writes again by itself.** The next write passes when there is room: no restart. `/healthz` is `503` (`writes are refused: the disk is nearly full`) while new data is refused and `200 ok` again after, so a load balancer can send exports elsewhere.
* **The log** has one line when the state changes, and no line for each request: `the disk is nearly full: ... New spans and scores are refused (503)`, then `there is room on the disk again: writes are taken again.`
* **When the writer of a store fails all the same** (another program filled the volume, `--min-free-mb 0`, a disk error): `/healthz` says `writes are refused: the store cannot write`, the log says why, writes are `503`, and queries answer from the last commit. The server then opens the store again by itself, as a restart does, when the volume has the room that the open needs (two times the write log, and the reserve): at once, then with a wait that doubles from 1 s to 30 s. While the store does not open for writing it is open read-only. No accepted export is lost: one that was answered `200` is in the write log, and the open applies it. (With tenants: the store of a tenant is opened again at the next request for it.)
* **A start on a full disk.** A server whose store cannot be opened for writing because the volume has no room starts read-only, says so in its log, and opens the store for writing by itself when there is room. (A store that stopped between its two commits opens only for writing, and that needs a little room: on a volume with not one block free the server starts with no store, every request is a `503` that says why, and it opens the store when there is room.) A store that does not open for another reason (another server on it, a damaged store, another format) stops the start, as before.
* **Limits.** The reserve is free space, not a file: another program on the same volume can take it; give the store its own volume. A server with `--s3` as the writer is not opened again by itself after its writer failed: restart it. Free space is read with `statvfs`: on a system without it, and on a volume that reports no size (some network and FUSE file systems), there is no reserve. Tested on macOS with APFS disk images (`tests/disk_full.rs`), not on Linux.

## Retention

`--retention 30d`. Every store then drops the spans that started more than 30 days ago (`Options::retention` and `Store::drop_before` in magpiedb). There is no route for it: the server does it on a timer.

* What goes: every span with a start before the cutoff. A trace with no span left goes with its summary and its scores. A trace with spans on both sides of the cutoff keeps the later spans, and its summary is made again from them. Session rows and sums stay exact.
* The cutoff is `now - retention` by the server's clock, rounded DOWN to a whole hour. A store looks when it opens and then every 10 minutes. So a span is gone at most 1 hour and 10 minutes after it got too old, plus the time the drop takes.
* Tenants: a store drops only while it is open, and the store of a tenant with no requests is closed. So the server opens every tenant's store once per hour (at start, then every hour; `--max-open-tenants` still holds, and `--tenant-idle-secs` closes them again). For such a tenant a span is gone at most about 2 hours and 10 minutes after it got too old. Not measured: how long that hourly round takes with many thousands of tenants.
* One value for all stores today. Each tenant's store is opened with its own options (`Tenants::get` in `src/tenants.rs`), so a retention per tenant is a small change there; where the value comes from (the key file, a config file) is not decided.
* Old data goes as whole files, with no rewrite. The one file per store that crosses the cutoff keeps its old spans on disk (not in any answer) until all of it is old. If that is more than 7 days away (a store with little traffic), the file is written again without them when a third of it is old. So there is no fixed time by which the bytes of a dropped span have left the disk.
* Without the flag nothing is dropped. A server started again without the flag keeps what is there.

## Host names

DNS rebinding: a web page of `rebind.example`, a name whose owner points it at `127.0.0.1`, is the same origin as the server for the browser, so the cross-site rule ([Query API](https://docs.magpiedb.com/reference/http-api.md#query-api)) lets it pass, and with no keys that page could read and write. Before this rule a score was written so (`200`). So a server with no keys on a loopback address (the default) answers only requests sent to `localhost` or an IP address (`127.0.0.1`, `[::1]`, `10.1.2.3`; any port), on every route, the viewer and `/healthz` too: else `403 HOST_NOT_ALLOWED` (gRPC `PERMISSION_DENIED`). An IP address passes: a rebound page always sends its own host name, and a page whose origin is an IP address and port is the server itself; so a Kubernetes probe (it sends the pod's IP) and a client that uses an address pass. The host is the `Host` header (HTTP/1.1) or `:authority` (HTTP/2), read as `name`, `name:port` or `[address]:port`; a name that only contains one of these (`127.0.0.1.rebind.example`) is not one of them, and no name is looked up in DNS.

* Keys stop a rebound page by themselves (it has no key): with keys there is no check, also with `--allowed-host` (D274; before, the Docker image refused service names also with keys).
* `--allowed-host <name>` (again for more names) adds a name and, with no keys, turns the check on for any address: a service name of compose or Kubernetes, a proxy on the same machine that keeps the public `Host`, an alias of `/etc/hosts`, a tunnel's name. The Docker image passes `--allowed-host localhost`, so with no keys the check is on in it too (it listens on `0.0.0.0`): give it the service name the clients use (section [Docker](https://docs.magpiedb.com/reference/server.md#docker)).
* On a non-loopback address with no keys and no `--allowed-host`, there is no check: the server cannot know its public names. Use keys there.
* `X-Forwarded-Host` is not read.

## Slow clients

A client that sends slowly, or opens a connection and sends nothing, holds a connection, and a write's place while its body arrives (D264; `src/serve.rs`). Each one has a deadline:

* HTTP: the headers of each request within `--header-timeout` (default 30 s), and a connection that waits for its next request is closed after the same time (hyper's header deadline: `axum::serve` sets no timer, and hyper has no deadline without one). The body within `--body-timeout` (default 60 s): else `BODY_TIMEOUT`, and the connection closes. That covers every route with a body: OTLP, scores, queries, deletes. OTLP (`POST /v1/traces`) answers `503` with `Retry-After: 1`, also when the body breaks off: the batch is not bad, and the OTLP spec sends a 503 again but drops a 408 or a 400. The other routes answer `408`. The clock starts when a write has its place (a write waits for a place before its body is read).
* gRPC: the server serves its HTTP/2 connections itself (`serve::grpc`, hyper with a timer), not with tonic's server. A connection that has sent no request within `--header-timeout` is dropped: it has nothing in flight (also one that sent nothing, or half of its HTTP/2 preface, for which hyper has no deadline). An export (its wait for a place, its body and its write) within `--body-timeout`: else `DEADLINE_EXCEEDED`, which OTLP clients send again (its write, once started, still ends). A connection that is quiet for 30 s gets a ping, and is closed when it does not answer in 20 s. At `--grpc-max-connection-age` (default 10 min), and at shutdown, a connection is closed gracefully: a GOAWAY, the requests in progress end, then it closes; clients open a new one by themselves. Before: tonic closed it by force at the age and 1 s, and an export in progress got `UNKNOWN`, which the OTLP spec says not to send again.
* Both ports: at most `--max-connections` (default 1024) connections at a time; with TLS a connection counts from its first byte, so its handshake too (the handshake has 10 s). The next connection waits in the system's queue (it is not refused) until one closes. The cap must fit the process's limit of open files (`ulimit -n`) with the files of the stores.
* Tested (`tests/hardening.rs`, with 1 s deadlines): headers that never end, an idle keep-alive connection, a body that never ends (a query, a score, an OTLP export), a fourth connection over a cap of 3, a gRPC body that never ends, a gRPC connection that sends nothing and one that sends half a preface, and a gRPC export in progress at the connection's age (it ends and is written). Before (the same probes on an earlier build of the server): each was still open after 6 s; the audit held one for 35 s.
* Not tested: many connections at once, or a slow reader of an answer. An answer is sent at the client's pace: an export to a client that reads slowly runs as long as the client reads (see [Limits](https://docs.magpiedb.com/reference/server.md#limits)).

## Limits

* An export has no time limit and no size limit, and it holds one thread of the server while it runs (also while a slow client reads). There is no limit on the number of exports at one time.
* No rate limit. Without `--auth keys` there is no authentication, and without `--tls-*` no TLS: then use it on a private network, or behind a proxy that does both.
* API keys have no expiry date and no per-key limits. To revoke a key, remove its line (in effect within about 2 s).
* One store, one directory. A second writer on the same directory is refused. With `--tenants-dir`, one store per tenant; one server per tenants folder. With `--s3`: one writer per prefix, and its own limits (section [S3](https://docs.magpiedb.com/reference/server-s3.md)).
* Tenants: a lock is held while a tenant store opens or closes, so other tenants' first requests wait for it (ms; longer if a close waits for a merge). Each active tenant commits on its own 0.5 s timer, so commits (and disk flushes) grow with the number of tenants that write at the same time.
* Not stored: span links, `traceState`, flags, dropped counts, scope attributes, schema URLs.
* `tags` are not set: OpenTelemetry has no standard name for them. `cost` has none either: it is read from `gen_ai.usage.cost` and OpenInference's `llm.cost.*`, or computed (`--prices`).
* Usage by kind of content (`gen_ai.usage.text.*`, `image.*`, `audio.*`) is not mapped: it stays in the attributes. One price table for all tenants; it is read when the server starts.
* The GenAI conventions are still in development. When they change, the mapping changes, and `MAPPING_VERSION` goes up. Spans already stored keep the old mapping.
* Numbers in JSON responses are plain JSON numbers. `costNanos` sums above 2^53 lose precision in JavaScript.
* Writes take a place before their body is read. At most 16 writes (OTLP exports over HTTP or gRPC, `POST /v1/scores`) read, decode and write at the same time, and at most 64 more wait for one of them; the next gets `429` with `Retry-After: 1` (gRPC `UNAVAILABLE`: the OTLP spec's code for "send it again later"), `BUSY`. Over HTTP the `429` comes at once, and the refused body is then read and dropped, with no place and no decode, at most `--max-body-bytes` and within `--body-timeout`: a client that sends its whole body before it reads the answer gets the `429`. Before, the connection closed with the body unread, and such a client got a reset instead (the launch proof, 128 clients: 2,585 answers `429` and 797 exports with no answer). A body that says it is longer than `--max-body-bytes`, or a request with `Expect: 100-continue`, is not read. gRPC needs no such read: HTTP/2 ends the one stream, and the client gets `UNAVAILABLE` (`tests/busy.rs`). A waiting write has not read its body: its bytes wait in the socket, not in the server. A write keeps its place until its work on the store ends, also when its client goes away. With keys, the key and its right are checked before the place is taken and before the body is read, on both doors (gRPC: before the message is decoded; a body that is not protobuf with no key is `UNAUTHENTICATED`, not a decode error). So the memory of writes in flight is at most 16 bodies (each at most `--max-body-bytes`, and its decoded and mapped form; see the next lines), not a count of waiting bodies. Measured (F99, the peak footprint of the server, one Mac): 16 full SDK batches at once (512 spans of 50 KB, 26 MB each) took 1.0 to 1.3 GB, and 16 bodies at the limit of 64 MiB 2.0 GB (JSON) to 2.7 GB (protobuf). On a small machine, lower `--max-body-bytes`. A slow client holds its place while its body arrives: `--body-timeout` ends that (section [Slow clients](https://docs.magpiedb.com/reference/server.md#slow-clients)). Deletes and purges do not take a place.
* What one OTLP request may become. The mapping puts a copy of the resource's attributes (and the scope's name and version) into every span: a request of 30 KB with 100 spans and one resource attribute of 8 KiB was 30 KB on the wire and about 800 KiB of spans (an audit of the server). So each request is measured after it is decoded and before anything is copied: its spans (at most `--max-spans-per-request`, default 100,000) and its bytes as protobuf, where each span counts with its resource and scope, and each scope with its resource (at most `--max-mapped-bytes`, default 2 x `--max-body-bytes`, so 128 MiB; it was 4 x a body limit of 16 MiB, 64 MiB, before D341: an ordinary batch maps to about its own size, and 4 x 64 MiB would let 16 small requests become 4 GiB of spans). Over either: `413` with `TOO_MANY_SPANS` or `MAPPED_TOO_LARGE`, gRPC `RESOURCE_EXHAUSTED` (the OTLP spec: a client does not send it again). Nothing of it is written. The mapped spans are not in the memory budget of the decode (`--ingest-memory-mb`): 16 small requests (130 to 160 KB each) with a resource of 100 KB, copied into each of their spans up to the cap, took the server to 5.6 GB at once with the cap of 128 MiB, and to 2.8 GB with the old 64 MiB (F99; about 2.6 times the mapped bytes). No SDK sends such a request; on a small machine, lower `--max-mapped-bytes` too. An `import` measures each OTLP line the same way, with a quarter of `--memory-mb` as the byte cap and no span cap.
* The decode of a request is measured before it is made (D269; `src/budget.rs`). A message with no field is 2 bytes of protobuf and a struct of 32 to 264 bytes once decoded: one body of 16 MiB with 8,388,592 empty spans took the server to 2.27 GB before this rule. Now every message of an OTLP/protobuf body is counted from its bytes, by the schema and with no allocation (spans, resources, scopes, attributes, values in lists, events, links, entity ids; a text is never read as a message): each message in a list costs twice its Rust size (the first of each list 4 times: a `Vec` of one item has room for 4; D276), and the body's bytes once more. A JSON body (D272, D275) costs 64 bytes for each value and each key and the bytes of each text, counted again for every OTLP `AnyValue` around it (serde reads an `AnyValue` through a `flatten` field, which copies the whole object, once more for each `AnyValue` it is in), each object what it becomes (in OTLP/JSON twice the struct of its list, the first of a list twice more: an attribute 128 bytes, a span 528; nothing for a struct its parent holds, such as the object of `"value"`; 528 under any other key; a score 1 KiB), and its bytes twice. Both counts are meant to be above the decode: `tests/budget_alloc.rs` measures the real decode of the reviews' bodies, of ordinary batches and of lists of one item, as JSON and as protobuf, and none is above its count (it counts the sizes the program asks for, not the allocator's rounding; the protobuf decode comes to 0.96 to 0.99 of its count in its worst shapes). An ordinary OTLP/JSON batch counts 6.0 to 20.5 times its bytes in the shapes measured (GenAI spans with long prompts 6.0, HTTP spans 13.2, DB spans with events 15.8, 40 small attributes a span 20.5; the decode takes 1.1 to 2.6 times), so one body of each of these shapes fits the default budget up to the old body limit of 16 MiB. With the body limit of 64 MiB, a JSON body of GenAI spans fits up to the limit (model calls of 50 KB, an SDK's full batch: 4.1 times; protobuf 1.0), and a JSON body of small spans up to about 512 MiB divided by its factor: about 38 MiB of HTTP spans, 32 MiB of DB spans, 25 MiB of spans with 40 small attributes; above, `413 DECODE_TOO_LARGE` (`results/anu87-sdk-batch/budget-alloc.txt`; an SDK sends at most 512 spans in one export by default). Not every shape: each item of an array attribute is in two `AnyValue`s and counts 3 times, so spans with an array of 100 ints count 38.4 times their bytes and are refused above about 13 MiB (F78, `results/anu84-hardening/json-count-factors-d276.txt`). The spans of an OTLP/JSON body (the items of `resourceSpans[].scopeSpans[].spans`) are counted before the decode, as for protobuf. An array directly in an array of an OTLP/JSON body is a `400` before the decode: serde reads a struct also from an array of its fields (a span as `[]`), which no OTLP encoder writes and which the count would not follow. Before (the third review, item 1), a 2 MB OTLP/JSON body with 30 nested `arrayValue`s was counted at 4 MB, decoded to about 1 GB and taken. A request over `--max-spans-per-request` is refused by that count, before the decode; one whose decode would cost more than `--ingest-memory-mb` (default 512) is `413 DECODE_TOO_LARGE` (gRPC `RESOURCE_EXHAUSTED`); the others take their cost from that budget and wait, with their place, until it is free (score writes too, at 1 KiB per object; an `import` line has a quarter of `--memory-mb`). Measured (F78, `results/anu84-hardening/decode-budget.json`): the 16 MiB body of empty spans is refused at a peak of 35 MB, 16 of them at once at 297 MB (their bodies). The count is an estimate of the decoder's memory, not a measure.
* The body limit: `--max-body-bytes` is 64 MiB by default, the default that the OTLP spec recommends for a server and a client (gRPC message and HTTP body). An SDK's batch processor sends up to 512 spans in one export (`OTEL_BSP_MAX_EXPORT_BATCH_SIZE`); 512 model calls of 50 KB are 26.0 MB as protobuf and 26.6 MB as JSON, which the old 16 MiB refused, and the client does not send a 413 again (`tests/sdk_batch.rs`). gRPC has the same limit (the door and tonic). A larger batch: raise `--max-body-bytes`, or make the SDK send fewer spans per export (`OTEL_BSP_MAX_EXPORT_BATCH_SIZE`). Over HTTP, the rest of a body over the limit by at most 64 MiB (or by `--max-body-bytes`, if larger) is still read and dropped after the `413`, within `--body-timeout`, with no place: a client that sends its whole body before it reads the answer gets the `413` (before, it got a broken connection, and some clients saw no answer). A longer body, or a request with `Expect: 100-continue`, is not read: the `413` comes at once and the connection closes.
* One list of a request has at most `--max-list-items` items (default 10,000; D271), counted before the decode, from the same count as the budget above: the attributes of a span, of the resource, of the scope, of an event or a link; the events and the links of a span; the values of an array or a kvlist in an attribute, also nested; the resources of a request, the scopes of a resource, the ids of an entity. OpenTelemetry SDKs keep 128 attributes of a span by default (`OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT`), so 10,000 leaves room. More: `413 LIST_TOO_LONG` (gRPC `RESOURCE_EXHAUSTED`: the OTLP spec says not to send it again; the same request would never fit), on HTTP (protobuf and JSON), gRPC and `import` (`--max-list-items` there too). The spans of a scope are not counted as a list: `--max-spans-per-request` caps them (a Collector puts thousands in one scope). In OTLP/JSON the count is of every array but `resourceSpans[].scopeSpans[].spans` (an array under another `"spans"` key counts: D273); the JSON query API and scores count every array. A protobuf field that holds one message and comes twice is a `400` before the decode: prost would join the lists of the copies. The JSON query API has the same cap, before its body is decoded: an array (`or`, `anySpan`, `traceIds`, ...), the words of a `words` text (a part ends at a space or an escape: never fewer than the engine finds), the scores of one write. Why: the macOS allocator keeps the memory of a decoded very long list after the request (F78): 16 requests of one span with 3,500,000 empty attributes left 3.4 GB before this cap; now they are refused and leave 24 MB, and 30 requests of 300 lists of 10,000 (the cap, within the decode budget) leave 258 MB with the kept blocks flat (`results/anu84-hardening/list-cap-retention.json`). Not measured on Linux.
* Speed was not measured. Do not read numbers from the tests.


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