# Ingest

> How the engine receives events, replay chunks, page snapshots, source maps and OTLP traces, what it checks, how it turns batches into objects, how it handles duplicates, and why it does not query the database to do it.

Applies to: the Sypnia engine (open source, self-hosted).  
Source: https://telemetry.docs.sypnia.com/architecture/ingest/

Ingest is the door of the engine. It receives what the SDKs send, checks it, and writes it to the Bucket. The browser SDK sends Sypnia's compact events; the server SDKs, the OpenTelemetry bridge and any OpenTelemetry exporter send traces in OTLP. Both pass the same gates. It analyses nothing. That is what keeps it fast, cheap and hard to break.

This page is the design behind the [Ingest API](https://telemetry.docs.sypnia.com/api/ingest). The API page says what to send; this one says what happens to it.

> **Note: About the code and the numbers**
>
> The Rust here is an excerpt of the engine's code. Limits are the ones in the API and event contracts. Times are budgets, not benchmarks.

## The HTTP surface

| Endpoint                   | Body                                                                              | Limit                                                     | Goes to                                                    |
| -------------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------- | ---------------------------------------------------------- |
| `POST /v1/ingest/events`   | A batch: up to 200 events and a `batch_id`                                        | 2 MiB after decompression                                 | The buffer, then a segment under `events/`                 |
| `POST /v1/ingest/replay`   | One replay chunk                                                                  | 4,000,000 bytes after decompression; 720 chunks a session | One object under `replays/`, written before the answer     |
| `POST /v1/ingest/snapshot` | One page snapshot                                                                 | 4,000,000 bytes after decompression                       | One object under `snapshots/`                              |
| `GET /v1/ingest/config`    | —                                                                                 | —                                                         | Answered from the cache: recording rules and `slow_down`   |
| `POST /v1/otlp/v1/traces`  | An OTLP `ExportTraceServiceRequest`, protobuf (what the server SDKs send) or JSON | 4,000,000 bytes; 2,000 spans                              | Decoded and mapped to server records, then the same buffer |

All five take an ingest key, `spk_…`, in `Authorization: Bearer` or, for `navigator.sendBeacon`, in the `key` query parameter (the OTLP endpoint takes the header only). An API token sent here is refused with `403 wrong_credential`, so a secret that ends up in a browser by mistake does not work quietly.

Source maps do not pass through ingest. Your CI asks the API for upload links with an API token, and uploads each file straight to the Bucket. See [the source-map section below](#source-maps-and-replay-chunks).

## The gates

A batch passes seven gates, in this order. Each one that fails answers at once with one error code, and the cheapest checks come first.

**Figure**: The seven gates of a batch. Gates 1 to 5 can refuse the whole request; gates 6 and 7 drop single events and say so in the answer. Gate 7 also refuses the whole request at Sypnia Cloud's hard stop on everything received.

1. **Key.** The project is found in a cache. Unknown or revoked: `401 unauthorized`. A credential of the wrong kind: `403 wrong_credential`.
2. **Origin.** Not on the key's list: `403 origin_not_allowed`.
3. **Rate limit.** Counted per key and address, in memory: `429 rate_limited`.
4. **Decode.** Gzip is detected by its first bytes and the size is capped: `400 invalid_body` or `413 payload_too_large`.
5. **Shape.** `events` must be a list of at most 200: `400 too_many_events`.
6. **Each event.** Cut, clean, drop or stamp. No error: what is dropped is counted in `dropped`.
7. **Quota.** `slow_down` is read from the cache. Usually no error: counted in `dropped_reasons.limit_reached`. At Sypnia Cloud's hard stop on everything received (`send: none`): `429 limit_reached`, nothing stored.

A line from Your app (SDK) through seven gates to the Buffer and the Bucket. The request is `POST /v1/ingest/events`. None of the seven gates queries the database. After gate 7 the lines wait in the Buffer; one segment goes to the Bucket at most 2 seconds later, and only then does the answer go back to your app: `200` with `accepted`, `dropped` and `slow_down`. If the Buffer cannot take the batch, the answer is `503 unavailable`.

### (1) The key

The key is looked up in a cache held in memory, not in Postgres. A key that is unknown or revoked gets `401 unauthorized`.

Notice the three ages in the lookup below. A hit is used as it is for 60 seconds. A miss asks Postgres once and remembers «no such key» for 60 seconds, so a wrong key cannot be used to hammer the database. And when Postgres does not answer, an entry up to one hour old is still good.

`crates/sypnia-ingest/src/project_cache.rs`

```rust
impl ProjectCache {
    /// The project behind an ingest key. One hash-map read on the hot path.
    pub async fn lookup(&self, key: &IngestKey) -> Result<Arc<ProjectEntry>, IngestError> {
        let now = self.clock.now();
        if let Some(slot) = self.entries.get(key) {
            match slot.value() {
                Slot::Known(entry) if entry.loaded_at + FRESH > now => return Ok(entry.clone()),
                Slot::Unknown { since } if *since + NEGATIVE > now => return Err(IngestError::Unauthorized),
                _ => {} // stale: refresh below
            }
        }
        match self.db.project_for_key(key).await {
            Ok(Some(entry)) => {
                let entry = Arc::new(entry);
                self.entries.insert(key.clone(), Slot::Known(entry.clone()));
                Ok(entry)
            }
            Ok(None) => {
                self.entries.insert(key.clone(), Slot::Unknown { since: now });
                Err(IngestError::Unauthorized)
            }
            // Postgres is down: keep serving what we knew, for at most an hour.
            Err(_) => match self.entries.get(key).as_deref() {
                Some(Slot::Known(entry)) if entry.loaded_at + STALE_OK > now => Ok(entry.clone()),
                _ => Err(IngestError::Unavailable),
            },
        }
    }
}
```

A long-running process also refreshes every entry in the background each 60 seconds, so in practice the request never waits for Postgres. That is how a revoked key is refused within one minute, as [Projects, environments, keys and tokens](https://telemetry.docs.sypnia.com/concepts/projects-keys-and-tokens) promises.

### (2) The origin

If the request has an `Origin` header and the key's project has a list of allowed origins (`settings.allowed_origins`, one list per project, for all its keys), the origin must be in the list, or the answer is `403 origin_not_allowed`. A request with no `Origin`, such as one from a server SDK, passes: a key used from a server is protected by its rate limit, not by a header the sender controls.

One layer owns CORS, and it is the engine. The system this comes from learned why: its function URL and its handler both added CORS headers, the browser rejected the answer **after** the data was stored, the SDK retried, and batches arrived twice. In the AWS template the address in front of the functions adds no CORS headers of its own.

The four routes a browser calls, `/v1/ingest/events`, `/replay`, `/snapshot` and `/config`, answer CORS this way:

| Request                                      | Answer                                                                                                                                                                                                                                                                                         |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A preflight: `OPTIONS` with `Origin`         | `204`, with `Access-Control-Allow-Origin: <that origin>`, `Access-Control-Allow-Methods: GET, POST, OPTIONS`, `Access-Control-Allow-Headers: authorization, content-type, content-encoding` and `Access-Control-Max-Age: 86400`. A preflight carries no key, so it is answered for any origin. |
| Any request with `Origin`, refusals included | `Access-Control-Allow-Origin: <that origin>`, `Vary: origin` and `Access-Control-Expose-Headers: retry-after, sypnia-request-id`, so the SDK can read `Retry-After` and a refusal. `allowed_origins` is checked here, on the request itself: `403 origin_not_allowed`.                         |

`/v1/sdk.js` answers `Access-Control-Allow-Origin: *`. OTLP has no CORS: servers send it, and servers do not preflight.

### (3) The rate limit

Each key has a number of requests a minute from one address (default 600, `rate_limit.ingest_per_minute`). The counter is a token bucket in the memory of the process. The address is read from the connection, or from the forwarding header when `trusted_proxy_hops` says a proxy is in front. It is used for this count and nowhere else: it is not written to an event, a log line or a row.

Because the counter is per process, several processes or functions each count on their own, and the real limit is higher than the setting. The alternative is a shared counter in Postgres or in another service, on the path of every request. A rate limit is a guard against a runaway loop, not a bill; an approximate one is enough.

### (4) Decoding

The body may be gzip. Ingest detects it from the first two bytes, `1f 8b`, whatever the `Content-Type` says, because `sendBeacon` cannot set `Content-Encoding`. It decompresses as a stream and stops at the limit, so a small body that expands to gigabytes costs 2 MiB of memory and a `413`, not the process.

**On AWS, a gzipped body must say `Content-Encoding: gzip`.** A Lambda function URL hands a body of a text type (`application/json`, `text/plain`) to the function as a string. The bytes of a gzip stream are not valid UTF-8, so they are replaced before the engine sees them, and the body answers `400 invalid_body`. With `Content-Encoding: gzip`, or a binary type, the function URL passes the bytes in base64 and the engine reads them. Measured on 2026-11-16: the same gzipped replay chunk answered `400 invalid_body` without the header and was stored with it. So the browser SDK sends `Content-Encoding: gzip` with every gzipped `fetch` body, from version 0.1.1, and never gzips a `sendBeacon` body, which stays uncompressed `text/plain`. Anything else you send to an engine on AWS follows the same rule. The engine still detects gzip by its first bytes, for every other shape.

### (5) and (6) The shape, then each event

`events` must be a list of at most 200. After that, each event is judged on its own. One bad event never costs the rest of the batch.

| What ingest finds                                                                                 | What it does                                                                             |
| ------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
| A field the contract does not list                                                                | Keeps it, as sent                                                                        |
| A `type` the contract does not list                                                               | Keeps the event. Only the parts that know the type will read it                          |
| A string longer than its limit                                                                    | Cuts it to the limit                                                                     |
| A listed field with the wrong type or a value outside its list                                    | Removes the field, keeps the event                                                       |
| A required field missing or unusable: no `type`, `ts` not positive, a browser event without `sid` | Drops the event: `invalid`                                                               |
| A vital outside its plausible range (an LCP over 120 s, an INP over 60 s, a CLS over 10)          | Drops the event: `invalid`                                                               |
| `ts` more than 7 days in the past                                                                 | Drops the event: `too_old`                                                               |
| An event from a route in the project's blocked routes                                             | Drops the event: `blocked_route`                                                         |
| An event of type `server_request`, `server_spans` or `server_error`                               | Drops the event: `otlp_only`. Those records are written by ingest itself from OTLP spans |
| `prj`, `rcv` or `bid` sent by the app                                                             | Replaces them with the engine's own                                                      |

The plausibility caps exist twice on purpose, in the SDK and here. Measured on the system this comes from: two browsers once reported INP values of 5 to 7 days and dragged a p75 to the top of the scale.

### (7) The quota

The cache entry carries the project's `slow_down`, decided elsewhere (see [Data flow](https://telemetry.docs.sypnia.com/architecture/data-flow#back-pressure-and-the-slow-down-signal)). When it says `send: failures`, ingest keeps errors and failed requests and counts the rest as `limit_reached`. The answer carries the same `slow_down`, so the SDK stops sending what would be dropped.

When it says `send: none`, the whole request is refused with `429 limit_reached`, the same `slow_down` beside the error and a `Retry-After` that runs to `until`, and nothing is stored. That is the hard stop on everything received, counted or not, failures included, at `limits.received_per_month`. It exists only on Sypnia Cloud: a self-hosted engine has no such limit and no setting for one, so its `slow_down` never says `none`. The same check runs on every ingest route: events, replay chunks, page snapshots and OTLP.

## The handler

This is the whole request, in order. Notice two things: nothing in it awaits Postgres, and the last `await` returns only when the segment that carries these events is in the Bucket.

`crates/sypnia-ingest/src/events.rs`

```rust
pub async fn ingest_events(
    State(ingest): State<Arc<Ingest>>,
    key: IngestKeyAuth,                       // Bearer header or ?key=; an sps_ token is 403 wrong_credential
    origin: Option<TypedHeader<Origin>>,
    ClientAddr(addr): ClientAddr,
    body: Bytes,
) -> Result<Json<IngestResult>, IngestError> {
    let project = ingest.projects.lookup(&key.0).await?;            // (1) 401
    project.check_origin(origin.as_deref())?;                       // (2) 403
    ingest.limiter.check(&project.key_id, addr)?;                   // (3) 429
    let batch: RawBatch = decode(&body, MAX_BATCH_BYTES)?;          // (4) 400, 413
    if batch.events.len() > MAX_EVENTS_PER_BATCH {
        return Err(IngestError::TooManyEvents);                     // (5) 400
    }
    if project.slow_down.refuses_all() {                            // (7) Sypnia Cloud's hard stop: send none
        return Err(IngestError::LimitReached(project.slow_down.clone())); // 429, nothing stored
    }

    let now = ingest.clock.now();
    // No batch_id? The body's own hash stands in, so an identical retry is still caught.
    let batch_id = batch.batch_id.unwrap_or_else(|| BatchId::from_content(&body));
    let mut lines = Lines::new(&project.id, &batch_id, now);
    let mut dropped = Dropped::default();

    for raw in batch.events {
        match validate(raw, &project, now) {                        // (6) cut, clean, stamp
            Ok(event) if project.slow_down.allows(&event) => lines.push(&event),
            Ok(_) => dropped.add(Reason::LimitReached),             // (7)
            Err(reason) => dropped.add(reason),
        }
    }

    let accepted = lines.len();
    if accepted > 0 {
        // Returns when the segment holding these lines exists. 503 if it could not be written.
        ingest.intake.append(lines).await?;
    }
    Ok(Json(IngestResult {
        accepted,
        dropped: dropped.total(),
        dropped_reasons: dropped.into_map(),
        slow_down: project.slow_down.clone(),
    }))
}
```

## From batches to objects

One object per batch would be the simplest design and the most expensive one. Measured on the system this comes from: object writes cost more than object storage. So batches are grouped.

**Figure**: Group commit. Batches that arrive within the same 2 seconds leave in one object, and all of them are answered when it exists.

1. The buffer: one open segment per project and environment. Batches from browser A (0.2 s), shop-api (0.6 s) and browser B (1.4 s) wait in it. It closes at 2 s, or at 4 MiB, whichever comes first.
2. One `PUT` writes the closed buffer to the Bucket as one object: 19 events from 3 batches.
3. Every request that put lines in the object is answered `200`, all at the same moment.
4. After the answers, one ledger row goes to Postgres.

Three sources on the left: browser A, browser B and shop-api (a server SDK). Each sends a batch into the buffer of `prj_5k2m9x4q7w1z · production`, where time runs from 0 s to 2 s: batch `0b9f…` with 6 events arrives at 0.2 s, batch `5d0c…` with 2 events at 0.6 s, batch `71aa…` with 11 events at 1.4 s. Each one waits until the buffer closes. The buffer becomes the file `20260312T091216Z-7f3a9c.ndjson.gz`, which goes to the Bucket in one `PUT`; then the three answers fan back to the three sources.

The buffer (1) is one open segment per project, environment and hour. The hour is the one the events happened in, when that is at most 48 hours before they arrived and at most 2 minutes after; otherwise the hour they arrived. Ingest groups a batch's lines by it, so a phone that sends last night's events fills a segment of last night's hour, written into that hour's folder and named by when it was written. See [Late and out-of-order events](https://telemetry.docs.sypnia.com/architecture/aggregation#late-and-out-of-order-events). A segment closes when the first of two things happens:

| Trigger                   | Value     | Why this value                                                                    |
| ------------------------- | --------- | --------------------------------------------------------------------------------- |
| Time since its first line | 2 seconds | Small against the 120-second budget, and at most 30 objects a minute per project  |
| Size before compression   | 4 MiB     | A worker reads a segment whole into memory to scan it; this keeps that read small |

A third limit protects the process: if more than 32 MiB of lines are waiting to be written, across all projects, new batches get `503 unavailable` with `Retry-After: 2` until the Bucket catches up. One project may hold at most 8 MiB of those 32: past that, only its own batches get the `503`, so a flood from one project cannot fill the buffer for the others.

When a segment closes it is written with one `PUT` (2), and every request that put lines in it is answered (3). So a client that sends one batch and waits for the answer before the next waits up to 2 seconds a batch. The SDKs send in the background and nobody waits; a backfill or an import must send many batches in parallel (32 at once works well) so they share segments. Then, off the request path, one row goes into the `segments` ledger (4). If that insert fails it is kept and tried again; a worker that starts also lists the last two hours of each project in the Bucket and adds any segment the ledger does not know.

Notice in the excerpt that the lock is never held across an `await`, and that every waiter gets the result of the same write: either all the batches of a segment are stored, or none is and each SDK retries its own.

`crates/sypnia-ingest/src/buffer.rs`

```rust
#[async_trait]
impl Intake for Buffer {
    async fn append(&self, lines: Lines) -> Result<(), IntakeError> {
        let (done, wait) = oneshot::channel();
        let scope = lines.scope(); // project, environment, and the hour its events happened (up to 48 h back)
        let full = {
            let mut open = self.open.lock(); // parking_lot: short, never held across an await
            // 32 MiB in all, 8 MiB for one project: a flood from one project is refused alone.
            if self.waiting.would_exceed(&scope, lines.bytes()) {
                return Err(IntakeError::Full); // 503 with Retry-After
            }
            let segment = open
                .entry(scope.clone())
                .or_insert_with(|| OpenSegment::new(self.clock.now()));
            segment.push(lines, done);
            segment.bytes() >= MAX_SEGMENT_BYTES
        };
        if full {
            self.flush(&scope).await; // the size trigger; a timer task covers the 2 seconds
        }
        wait.await.map_err(|_| IntakeError::Closed)?
    }
}

impl Buffer {
    async fn flush(&self, scope: &Scope) {
        let Some(segment) = self.open.lock().remove(scope) else { return };
        let key = Keys::new(&self.prefix, scope).segment_in(scope.hour(), self.clock.now(), self.writer);
        let (body, summary, waiters) = segment.finish(); // gzip, counts, batch ids

        let result = self.store.put(&key, body, PutOptions::ndjson_gzip()).await;
        if result.is_ok() {
            self.ledger.register(SegmentRow::new(scope, &key, summary)); // queued, retried, never awaited here
        }
        for waiter in waiters {
            let _ = waiter.send(result.clone().map_err(IntakeError::from));
        }
    }
}
```

### The same thing on AWS

A function cannot keep an open segment between two requests, and many copies of it run at once. So `Intake` has a second implementation there: a queue.

|                                                    | One process (`serve`)                                                                                         | AWS functions                                                                                                                                                                                                                                        |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Intake::append`                                   | Adds to the in-memory buffer, waits for the `PUT`                                                             | Sends the validated lines as one queue message, waits for the queue to confirm                                                                                                                                                                       |
| Who writes the segment                             | The same process, 2 seconds later                                                                             | The worker function, woken by the queue with up to 10 seconds of messages                                                                                                                                                                            |
| If the segment or its ledger row cannot be written | The batches get `503`; a ledger row is kept and retried, and found by listing the Bucket when a worker starts | The message is not deleted: the queue delivers it again, and after 5 deliveries parks it in the dead-letter queue. See [What happens when something fails](https://telemetry.docs.sypnia.com/architecture/reliability#queues-and-dead-letter-queues) |
| The answer means                                   | The events are in the Bucket                                                                                  | The events are in the queue, which keeps them for 4 days                                                                                                                                                                                             |
| Segment name and content                           | Identical                                                                                                     | Identical                                                                                                                                                                                                                                            |

A batch larger than 192 KiB after compression does not go into a message: ingest writes it as its own segment and sends a message that only names it. The alternative for AWS was a managed delivery stream, as in the system this comes from. It was left out because it cannot name objects by project without an extra feature that buffers for at least 60 seconds, half of the 2-minute budget.

## Duplicates and idempotency

Networks retry. A browser can send a batch, lose the answer and send it again. Each kind of upload has one rule that makes the second arrival harmless.

| Upload                     | What makes it idempotent                                                                                                                                                                                                                                     |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| A batch of events          | `batch_id`. Every stored line carries it as `bid`. The first worker that scans a segment records its batch ids; a batch id seen before, in any segment of the last 48 hours, is skipped by every reader. The lines stay in the object; they are not counted. |
| A batch without `batch_id` | Ingest uses the SHA-256 of the body as the id. A retry of the same bytes is caught; the same events re-sent in a different body are not.                                                                                                                     |
| A replay chunk             | The key is `replays/<sid>/<seq>`. The same `seq` again replaces the object.                                                                                                                                                                                  |
| A page snapshot            | The key ends in the snapshot's own `ts`. The same snapshot again replaces the object.                                                                                                                                                                        |
| An OTLP request            | The SHA-256 of the body. OTLP exporters retry with the same bytes.                                                                                                                                                                                           |

Dedupe happens when segments are read, not when batches are received, for one reason: receiving must not depend on Postgres. The price is that a duplicated batch takes space in the Bucket. That is cheap; a doubled count is not.

## Source maps and replay chunks

**Replay chunks** go through ingest, one request per chunk, because ingest must check three things before storing one: that the route is not in the project's blocked routes (`403 not_recordable`), that the session has fewer than 720 chunks (`422 session_full`), and that the project is inside its replays limit and, on Sypnia Cloud, its limit on everything received (`429 limit_reached`). The chunk is written before the answer, with `Content-Type: application/json` and `Content-Encoding: gzip`. Ingest does not look inside it.

The 4,000,000-byte limit is not arbitrary. On AWS a function receives at most 6 MB in one request; the SDK's chunks of 200 KB and this cap keep a good margin under it.

**Source maps** never pass through ingest. A deploy of a large app is hundreds of files and, measured on the system this comes from, about 109 MB. So the upload is in three steps, all with an API token of scope `ci`, which can register releases and upload source maps and nothing else (`admin` works too):

1. Your CI calls `POST /v1/releases/{version}/sourcemaps` with the list of files.
2. The API answers with one signed upload link per file, valid for 15 minutes (`storage.presign_ttl_seconds`).
3. Your CI uploads each file straight to the Bucket, under `sourcemaps/<release>/`, and the `index.json` that maps each built file to its map.

`sypnia sourcemaps upload` does the three steps for you.

## OTLP intake

`POST /v1/otlp/v1/traces` is where every server trace arrives: from `@sypnia/telemetry/node` and `@sypnia/telemetry/next`, from the [`@sypnia/telemetry/otel`](https://telemetry.docs.sypnia.com/sdks/otel-bridge) bridge, and from any OpenTelemetry exporter in any language. They all speak the same protocol, so ingest has one path for them. It turns the spans into the engine's server records, `server_request`, `server_spans` and `server_error`, defined in the [event schema](https://telemetry.docs.sypnia.com/reference/event-schema), and writes them as NDJSON lines into the same buffer and the same segments as the browser's events. After this step nothing downstream knows who sent the spans.

The work lives in one module of the ingest crate:

```text
crates/sypnia-ingest/src/otlp/
├── mod.rs       the handler: gates 1 to 4, then decode, map, buffer, answer
├── decode.rs    ExportTraceServiceRequest from protobuf or JSON (types generated by prost from opentelemetry-proto)
├── map.rs       spans → server_request, server_spans and server_error lines
└── redact.rs    the attribute deny-list and the redaction of failure messages
```

### The steps

1. **Gates 1 to 4, unchanged.** The key (header only), the origin, the rate limit, then decoding: gzip by its first bytes, the size capped at 4,000,000 bytes as a stream.
2. **Decode.** `application/x-protobuf` is decoded with the types `prost` generates from `opentelemetry-proto`; `application/json` with the same types and OTLP's JSON rules (ids in hex, times as strings of nanoseconds). Anything else is `415 unsupported_media_type`; a body that is not an `ExportTraceServiceRequest` is `400 invalid_body`. More than 2,000 spans in one request is refused whole.
3. **Clean each span.** At most 64 attributes, values cut at 256 characters (4,000 for `exception.stacktrace`, 500 for messages, 2,000 for `sypnia.db.message` and for the status message of a span that carries it). `url.query`, `url.full`, `db.query.text` and any attribute whose name contains `authorization`, `cookie`, `password`, `secret` or `token` are removed. A span with a trace id that is not 16 bytes, or a span id that is not 8, is refused and counted.
4. **Redact.** The status message of a failed call is redacted with the same rule the server SDKs apply before sending: e-mail addresses, URLs, UUIDs, quoted values, long tokens and every run of digits are replaced. For spans from a Sypnia SDK this changes nothing; for other exporters it is the only redaction. One exception: a span that carries `sypnia.db.message` keeps that attribute and its status message as sent. Only the Sypnia server SDKs set it, for a database's error message, which the app chose to keep with `captureDbErrors` (on by default); see [Database error details](https://telemetry.docs.sypnia.com/sdks/node#database-error-details).
5. **Map.** Spans are grouped by trace id and `service.name`, then written as records (table below).
6. **Quota.** The project's `slow_down` is read from the cache, as in gate 7: with `send: failures`, only records that carry a failure are kept; with `send: none` (Sypnia Cloud's hard stop on everything received), the request is refused with `429 limit_reached`, `Retry-After` and `Sypnia-Slow-Down: send=none; until=…`, and nothing is stored.
7. **Answer.** An `ExportTraceServiceResponse` in the encoding of the request: empty when everything was stored, `partialSuccess` with `rejectedSpans` and the reason otherwise, as the protocol requires. At a usage limit the answer also carries the header `Sypnia-Slow-Down: send=failures; until=…`, which the Sypnia SDKs obey.

### From spans to records

The attributes are in the [semantic conventions](https://telemetry.docs.sypnia.com/reference/semantic-conventions); this is what `map.rs` does with them.

| In the OTLP request                                                                                               | Becomes                                                                                                                                                                                                                                                                                  |
| ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Resource `service.name`, `service.version`, `deployment.environment.name` (or the older `deployment.environment`) | `service`, `ver` and `env` of every record; `env` is `production` when missing                                                                                                                                                                                                           |
| A span of kind `SERVER`                                                                                           | One `server_request`: `tid`, `span`, `parent`, `method`, `route` from `http.route`, `path` from `url.path`, `status`, `dur`, `sid` from `session.id`, `person` from `user.id`, `account` from `sypnia.account.id`, `cold` from `faas.coldstart`                                          |
| The other spans of the same trace and service in the same request                                                 | That record's `spans[]`: `db` when the span has `db.system.name`, `http` when it has `http.request.method`, else `internal`; at most 200 kept, the rest counted in `span_n` with `sypnia.dropped_spans`                                                                                  |
| Spans whose `SERVER` span is not in the request                                                                   | One `server_spans` record per trace and service. Only exporters that split one request's spans across exports cause it; the Sypnia SDKs export a request's spans together                                                                                                                |
| Span status `ERROR`, or no answer, `400` or `500`+ on a child span                                                | That span's `status: error`, with `code` from `http.response.status_code` or `db.response.status_code`, and one `server_error` with `src: span`                                                                                                                                          |
| An `exception` span event                                                                                         | One `server_error`: `name` from `exception.type`, `msg` from `exception.message`, `stack` from `exception.stacktrace`, `src` from `sypnia.error.source` (`uncaught` when missing), `digest` from `sypnia.error.digest`. `tid` is null when the span carries `sypnia.error.standalone`    |
| A `SERVER` span that answered `500` or above with no other failure                                                | One `server_error` with `src: status`                                                                                                                                                                                                                                                    |
| A `SERVER` span with `sypnia.partial`                                                                             | A partial `server_request`; the full span with the same span id replaces it when it arrives, and a partial record not replaced within 15 minutes becomes a timeout (see [Problem grouping](https://telemetry.docs.sypnia.com/architecture/problem-grouping#from-a-failure-to-a-problem)) |
| Other span events, links, `tracestate`, baggage                                                                   | Dropped                                                                                                                                                                                                                                                                                  |

The fingerprint of a `server_error` is `sypnia.error.fingerprint` when the sender set it, and otherwise computed here with the same algorithm the SDKs use (see [Problem grouping](https://telemetry.docs.sypnia.com/architecture/problem-grouping)), so the same failure is one problem whoever sent it.

An OTLP request that arrives twice is stored once: its id is the SHA-256 of the body, the same rule as a batch without `batch_id`, because OTLP exporters retry with the same bytes.

Spans of one trace can arrive in different requests and from different services. Ingest does not wait for them: each request is mapped on its own. The roll-up joins everything that shares a `tid` when it builds the `traces` index, and adds the browser's part: each browser `request` event becomes a span of kind `browser` whose id is the event's `span`, the parent id the browser put in `traceparent`. A span whose parent is missing hangs under the root.

## Why ingest does not query Postgres

Three reasons, in order of weight.

1. **Availability.** If receiving needed the database, every database problem would be data loss. As designed, a Postgres outage costs freshness and nothing else.
2. **Connections.** The system this comes from once exhausted its connection pooler: each copy of a request-serving function opened its own pool. Ingest is the most copied part of the engine; keeping it off the database removes the largest source of connections.
3. **Latency.** A hash-map read takes less than a microsecond. A query takes a network round trip, on every batch from every browser.

What ingest reads instead is small, and all of it comes from the cache entry of the key:

| Cached per ingest key                        | Used for                                         | How fresh |
| -------------------------------------------- | ------------------------------------------------ | --------- |
| Project id, key id, `revoked_at`             | Gate 1                                           | 60 s      |
| The project's `settings.allowed_origins`     | Gate 2                                           | 60 s      |
| `rate_limit_per_minute`                      | Gate 3                                           | 60 s      |
| Blocked routes, replay rules, sampling rates | Gate 6, `/v1/ingest/config`                      | 60 s      |
| `slow_down`                                  | Gate 7 and the answer                            | 60 s      |
| `has_server`                                 | Nothing in ingest; it rides along for the worker | 60 s      |

The only write ingest makes to Postgres is the ledger row: **one row per flushed segment**, not one per request and not one per event. It happens after the answer, on one connection per process, and it is allowed to fail. A request never waits on Postgres.

If Postgres is down when a segment is flushed, the segment is still written to the Bucket and the SDKs are still answered. The ledger row is kept in memory and retried; if the process dies before it succeeds, a worker recovers it by listing the Bucket and adding every segment the ledger does not know. Until then the events are safe and not yet counted.

### Logs

Ingest writes one JSON line per request: status, events accepted and dropped, bytes, milliseconds. Never the key, the address or the body. Requests that succeed with nothing dropped are sampled at 1 %. Measured on the system this comes from: logging every success cost about 18 MB of logs a day for one app.

## What changed from the system this comes from

| There                                                                                   | Here                                                  | Why                                                                                                               |
| --------------------------------------------------------------------------------------- | ----------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| A signed-in user's token, verified against the app's auth service                       | A public ingest key, allowed origins and a rate limit | Brief §10.2: the ingest key is the only credential for sending                                                    |
| No dedupe: a retried batch was stored and counted twice                                 | `batch_id` on every line                              | The CORS incident of 2026-09-30                                                                                   |
| No rate limit, no quota                                                                 | Both                                                  | A public key needs them                                                                                           |
| No limit on how old `ts` may be                                                         | 7 days                                                | An old clock or a stuck queue must not rewrite last month                                                         |
| Server records skipped ingest and wrote to the stream directly, in the app's own format | Everything goes through ingest; servers send OTLP     | One place stamps the project; a server needs only a key and a URL, and speaks a protocol any language already has |
| Unknown fields removed by an allow-list                                                 | Unknown fields kept                                   | Brief §10.4: schema on read                                                                                       |

## Next
