diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 307f64a..fe1ab3c 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -1,15 +1,22 @@
# Contributing
-Keep the collector small and its claims reproducible.
+Explain what a change does and how you checked it in the pull request.
-1. Read [the delivery contract](docs/delivery.md).
-2. Add a behavioural regression test before changing a failure path.
+1. Read [the delivery contract](docs/delivery.md) before changing ingestion behavior.
+2. Reproduce a failure with a regression test before fixing its path.
3. Run `make test`, `go vet ./...`, `go build ./...` and `make test-integration`.
- Run the Python/Node suites when changing examples or artifact auditing; see
+ For example or auditor changes, also run the Python/Node suites listed in
[development](docs/development.md).
-4. Explain the resulting behaviour and verification in the pull request.
+4. Describe the resulting behavior and verification, including limits that affect users.
-Integration tests create and destroy only their own isolated Compose projects.
-Do not reset a shared database, weaken durability for a benchmark, or add a
-performance claim without its raw results and environment metadata. Keep timing studies sequential, commit the measured code first and
-retain limited/unknown outcomes. Figure edits use [source/data and visual checks](docs/figures/README.md).
+Integration tests may create and remove only their own Compose projects. Keep
+shared databases and other runs intact. Commit measured code before a timing
+study, run studies sequentially, and keep unknown or limited outcomes in the
+report. Performance claims need raw results and environment settings; weakening
+durability changes the question. [Figure sources and checks](docs/figures/README.md)
+cover data accuracy and visual review.
+
+For documentation, explain the event or operator task before naming the internal
+mechanism. Define unfamiliar terms where they first matter. Give each diagram a
+question to answer, and keep measurement settings and unknown outcomes beside
+the result. Code examples must still run after a prose edit.
diff --git a/README.md b/README.md
index 78ac658..5cc6e6e 100644
--- a/README.md
+++ b/README.md
@@ -1,24 +1,24 @@
# IngestKit
-A self-hosted event collector for trusted application backends. Send JSON over
-HTTPS, buffer it in Redpanda, and store it in PostgreSQL with stable event IDs.
-The repository includes copyable clients, a transactional outbox, failure tests
-and reproducible experiments.
+Collect events from your backend and save them in PostgreSQL. A queue in between
+lets IngestKit keep accepting events during a temporary database outage.
-**HTTP 202 means broker acknowledgement. PostgreSQL storage is asynchronous.**
-Retry uncertain delivery with the same UUID and content; storage keeps one row
-per `(tenant_id,event_id)` and retains the first stored content.
+For example, your checkout service sends an `order_completed` event with a saved
+ID. Redpanda holds it in the queue until a background worker writes it to
+PostgreSQL. If the request times out, resend the same ID; the database keeps one
+row for that event. The API key selects the tenant, a label stored with your events.
-
+
-[Deployment](deploy/README.md) · [Application integration](docs/integration.md) ·
-[Operations](docs/operations.md) · [Engineering article](docs/article.md)
+HTTP 202 means the queue accepted the event. The database write happens
+separately. [Read the story of an event, an outage and a retry](docs/article.md).
-## Deploy
+## Run it on your server
-Use a Linux host with Git, Docker/Compose 2.24.4+, OpenSSL and curl. Point your
-own hostname at it and make ports 80/443 reachable. Replace `events.example.com`
-below with that hostname. Go is built inside Docker.
+You need a Linux host with Git, Docker/Compose 2.24.4+, OpenSSL and curl.
+Point a hostname you own at the server and allow traffic on ports 80 and 443.
+Replace `events.example.com` below with that hostname. Docker builds the Go
+programs, so you do not need to install Go on the server.
~~~sh
git clone https://github.com/feat7/ingestkit.git
@@ -27,16 +27,17 @@ deploy/configure.sh events.example.com
docker compose --env-file deploy/.env -f deploy/compose.yml up -d --build --wait
~~~
-Configuration is generated into ignored `deploy/.env` with mode 0600 and fresh
-secrets; existing files are never overwritten. Only Caddy publishes ports.
-See the [deployment guide](deploy/README.md) for DNS, resources and certificate
-prerequisites. Public certificate issuance requires working DNS/reachability;
-the automated HTTPS tests use a trusted private CA.
+The setup script writes fresh secrets to ignored `deploy/.env` with file mode
+0600, so only its owner can read it. It refuses to overwrite existing settings.
+Caddy handles HTTPS; the API, queue and database have no public ports. The
+[deployment guide](deploy/README.md) covers resources, DNS and certificates.
+Public certificates need working DNS and reachable ports; automated tests use
+a local certificate authority that the test client explicitly trusts.
-## Send and verify
+## Send an event and find it in the database
-For the initial generated key mapping, load the key without printing it and send
-the three checkout events:
+For the initial generated configuration, load the API key without printing it
+and send the three checkout events included in the repository:
~~~sh
INGESTKIT_API_KEY=$(sed -n 's/^API_KEYS={"\([0-9a-f]*\)":"default"}/\1/p' deploy/.env)
@@ -51,45 +52,54 @@ docker compose --env-file deploy/.env -f deploy/compose.yml exec -T postgres \
"SELECT tenant_id,event_id,event_type FROM ingestkit.events ORDER BY persisted_at DESC LIMIT 10;"
~~~
-Allow the consumer time to catch up before checking SQL. Repeating these fixed
-UUIDs still stores three logical events for the initial tenant. Use fresh UUIDs
-for new business events. Stop with the following command; named data volumes remain:
+Give the worker time to save the events before running the SQL query. Sending
+this fixture again still leaves three events for the initial tenant. For new
+business events, create new IDs. The database key is `(tenant_id,event_id)`:
+your API key selects the tenant, and your application supplies the event ID.
+The first content saved for that key stays in the table.
+
+Stop the services with this command. Docker keeps their named data volumes:
~~~sh
docker compose --env-file deploy/.env -f deploy/compose.yml down
~~~
-## Integrate
+## Send events from your application
-Copy the standard-library [Python or Node client](docs/integration.md) into a
-backend. For durable application delivery, run the [order/outbox example](examples/outbox/README.md):
-business state and the serialized event are saved in one SQLite transaction,
-then a separate dispatcher sends pending work with stable IDs. Keys stay in
-trusted backend configuration. See the [API reference](docs/api.md) for limits,
-responses and permanent versus uncertain failures.
+The [Python and Node examples](docs/integration.md) are small modules you can
+copy into a backend. They need no third-party packages. Keep the API key on
+your server and save each event's ID and content before sending it.
-## Inspect the evidence
+For events that must survive an application crash, try the
+[order and outbox example](examples/outbox/README.md). It saves an order and a
+pending event in the same database transaction. A separate command sends the
+pending events and can pick up where a previous process stopped. The
+[API reference](docs/api.md) explains request limits and which failures to retry.
+The [operator guide](docs/operations.md) covers backups, key rotation and a queue
+that stops making progress.
-The [corrected HTTPS study](benchmarks/results/selfhost-2026-11-04/README.md)
-records 25 configurations with three measured repetitions: database batching,
-payloads, duplicates, HTTP load, concurrency and three recovery scenarios.
-All acknowledged IDs reconciled with stored content; generator limits and
-ambiguous outcomes remain explicit. These local runs do not establish maximum
-capacity. Batch INSERT had the lower median than COPY/staging/merge in all 11 DB
-configurations, so the deployed writer now uses atomic batch INSERT.
+## Try an outage locally
-To try an isolated local walkthrough, use Docker and Go 1.24+:
+With Docker and Go 1.24+ installed, run:
~~~sh
make demo DEMO_FLAGS=-cleanup
make demo-recovery DEMO_FLAGS=-cleanup
~~~
-[Development and tests](docs/development.md) · [Experiment controls](benchmarks/README.md) ·
-[Delivery semantics](docs/delivery.md) · [Architecture](docs/architecture.md)
-
-This is a single-host deployment with one broker replica and finite log retention.
-It does not protect against losing the host/disk or a recovery gap beyond retained
-data. PostgreSQL rows have no automatic expiry; the operator owns backups, disk
-monitoring and retention. It provides ingestion and replay-safe storage, without
-an analytics UI, schema compiler or database row-level tenant policies.
+The second demo stops PostgreSQL, sends events, restarts the database and checks
+that the same IDs reached the table. The [experiment results](benchmarks/results/selfhost-2026-11-04/README.md)
+go further: 25 configurations, three runs each, with saved samples and explicit
+limits. The database comparison led to a simpler writer: batch INSERT had a lower
+median time than COPY/staging/merge in all 11 tested database configurations.
+Unknown delivery outcomes remain unknown in the reports; these runs do not
+establish maximum capacity.
+
+[Development and tests](docs/development.md) · [Run the experiments](benchmarks/README.md) ·
+[Delivery details](docs/delivery.md) · [How the components fit together](docs/architecture.md)
+
+This deployment runs on one host with one Redpanda replica and keeps queue
+records for seven days by default.
+Losing the host or its disks can lose data. An outage longer than the queue's
+retention can leave events unrecoverable. PostgreSQL rows do not expire
+automatically; plan backups, disk monitoring and database retention for your use.
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 9b8ca2f..e66b6a5 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -1,17 +1,22 @@
-# Experiments
+# Run and read the experiments
-Read the [corrected self-hosted study](results/selfhost-2026-11-04/README.md) for
-all 25 configurations, repetitions, controls and limits. The complete
-[COPY-writer reference](results/selfhost-copy-2026-11-04/README.md) is preserved
-separately. The final deployed writer uses batch INSERT, chosen after the first
-study favored it over COPY/staging/merge in all 11 database configurations.
+The experiments answer three questions: how to write batches to PostgreSQL,
+what happens at different HTTP loads, and whether saved events survive specific
+outages. A case is one fixed configuration, measured three times after warm-up.
+The registered study has 11 database cases, 11 HTTP cases and 3 recovery cases.
-## Run the registered study
+Start with the [current writer results](results/selfhost-2026-11-04/README.md).
+The [earlier COPY-writer study](results/selfhost-copy-2026-11-04/README.md) is also
+complete. Batch INSERT had a lower median write time than COPY/staging/merge in
+all 11 database cases, so the deployed worker changed to batch INSERT and the
+whole study ran again. These are local measurements with recorded limits.
-Use Go 1.24+, Docker/Compose 2.24.4+, Python 3.9+ and OpenSSL on the local experiment
-host. The driver starts one owned HTTPS deployment, trusts its extracted private
-CA, exposes only owned loopback observation ports, saves evidence and removes
-only its own resources. The deployment server itself does not need Go.
+## Run a small check before a full study
+
+The experiment host needs Go 1.24+, Docker/Compose 2.24.4+, Python 3.9+ and OpenSSL.
+The driver starts its own HTTPS deployment and trusts its extracted private CA.
+It publishes observation ports only on loopback, saves evidence, then removes
+only that run's services. A deployment server itself does not need Go installed.
~~~sh
# Small correctness subset; three repetitions per case, not publication evidence.
@@ -27,122 +32,133 @@ make bench-study STUDY_FLAGS='-out benchmarks/results/my-study -seed 42 -resume'
python3 benchmarks/audit_study.py benchmarks/results/selfhost-2026-11-04
~~~
-The command prints the chosen output path, each case and its status. An omitted
-path selects a fresh ignored `tmp/studies/` directory. Existing output is
-refused without `-resume`. Full runs require clean committed source; smoke may
-be explicitly marked dirty and is never publication timing evidence. Do not
-edit source, run concurrent test/plot workloads, or stop unrelated user services
-while timing a comparison. The recorded host had existing workloads, noted in
-its environment limitations.
+The command prints its output directory and each case's status. With no path,
+it chooses a fresh ignored `tmp/studies/` directory. An existing directory
+requires `-resume`. Full measurements need clean committed source. Smoke runs
+may be explicitly marked dirty and test correctness; they are not publishable
+timing evidence.
+
+Run timing studies one at a time. Keep source, concurrent tests and figure jobs
+unchanged during a comparison, and leave unrelated services alone. The recorded
+host had other workloads; that shared use is part of its reported limitations.
-## Fixed controls
+## What changes between cases
-Every configuration has three measured repetitions after warm-up. The database
-methods rotate order. The registry is deliberately not a full Cartesian product.
+Database methods rotate order across the three runs. These are matched sweeps,
+not every possible combination of settings.
-| Question | Configurations | Matched controls |
+| Question | Configurations | Settings kept the same |
| --- | --- | --- |
| SQL batching | Batches 1/10/50/100/500/1000 | 5,000 submissions/method, 256 B, no duplicates |
-| SQL payload | 1 KiB/16 KiB | Batch 100; compare with 256 B/batch 100 above |
-| Repeated IDs | 10/50/90% | Batch 100,256 B; compare with 0% above |
-| HTTP batching | Batches 1/10/100 | Offered 1,000 events/s, 256 B, 32 clients |
-| Offered load | 100/5,000/10,000 events/s | Batch 100,256 B, 32 clients;1,000/s baseline above |
-| HTTP payload | 1 KiB/16 KiB | Batch 10; compare with 256 B/batch 10 above |
-| Burst | Same total in first quarter of window | Batch 100,256 B, 32 clients |
-| Client concurrency | 8/64 clients | Batch 1, 1,000 offered/s, 256 B;32-client baseline above |
-| PostgreSQL outage | Stop requested 3s; start requested 8s | 15-second 500/s workload, batch 100 |
-| Consumer kill/restart | KILL requested 3s; start requested 5s | Same 15-second 500/s workload |
-| Outbox + broker outage | 100 durable application events, broker stopped 8s after stop completion | Failed attempt exceeds 5s; new dispatcher replays original UUIDs |
-
-Ordinary pipeline windows are ten seconds after two-second warm-up, with a
-30-second observation drain deadline and 50 ms target polling. Large payloads use
-batch 10 to fit the existing 1 MiB request cap. The selfhost study fixes API limit
-10,000 requests/s, info logging, broker 1 core/1 GiB and seven-day topic retention.
-Actual process arguments, topic/database settings and trusted HTTPS protocol are
-captured; no environment variable silently tunes matched cases.
-
-Payloads are reproducible varied ASCII JSON at the exact encoded byte length.
-Each case/repetition uses a recorded namespace and seed. Duplicate submissions
-reuse identical bytes/IDs. For SQL, generation/reset/warm-up/content verification
-are outside elapsed time. Single INSERT commits each row; batch INSERT and the
-independent COPY/staging/merge reference commit each batch against the same
-indexed table/conflict policy. Submitted/s and inserted unique/s differ when
-there are duplicates; those cases do less new-row work.
-
-## Interpret the populations
-
-- HTTP ACK latency: one sample per successfully acknowledged request.
-- SQL visibility upper bound: one sample per event first seen by the pending-ID
- observer after commit, from API receipt through completed SQL observation.
- It includes polling/query delay, not just database execution.
-- In-window ACK rate: only acknowledgements completed inside the target window,
- divided by that window. Late starts/ACKs are separate counters.
-- Verified stored rate: independent unique-row count divided by the full window,
- request tail, observation drain and final verification. It is not an intrinsic
- server-capacity estimate.
-- `ObservedEvents` identifies latency samples. `VerificationNS` records the final
- census overhead; rows found only then do not receive invented latency samples.
-
-The temporary pending-ID relation is connection-owned, not a timestamp cursor.
-Transactions committing out of order remain observable. Final ID/type/time/payload
-reconciliation is independent of observation bookkeeping and scopes only the
-owned namespace/IDs. It never truncates a shared table or cleans an unrelated run.
-
-`limited` retains generator misses, late schedules, request/ACK tails, rejected or
-ambiguous delivery, late polls and observer outages. A normal finite-window tail
-does not by itself diagnose saturation. Fewer attempted events means the driver
-missed its target; it does not mean the collector lost unattempted events.
-An ambiguous ID absent at the final deadline remains **unknown**, not proven
-undelivered. Acknowledged missing IDs, unexpected content/IDs or duplicate physical
-rows fail correctness; they cannot become a successful speed result.
-
-Receipt and SQL observation share the deployment clock; host monotonic time
-schedules load. Nearest-rank p50/p95/p99 are computed from their distinct raw
-populations. Slow polls/query duration/max gaps are reported. During the deliberate
-PostgreSQL outage only, the observer reconnects and rebuilds pending IDs while
-recording unavailable observations. No exact commit time is inferred in that gap.
-Fault timestamps record actual control requests/completions, not an assumed
-instant service recovery. Availability experiments are separate from capacity.
-
-## Artifacts and resume
+| SQL payload size | 1 KiB/16 KiB | Batch 100; compare with 256 B/batch 100 above |
+| Repeated IDs | 10/50/90% | Batch 100, 256 B; compare with 0% above |
+| HTTP batching | Batches 1/10/100 | Target 1,000 events/s, 256 B, 32 clients |
+| HTTP sending rate | 100/5,000/10,000 events/s | Batch 100, 256 B, 32 clients; 1,000/s baseline above |
+| HTTP payload size | 1 KiB/16 KiB | Batch 10; compare with 256 B/batch 10 above |
+| Burst | Same total sent in the first quarter of the window | Batch 100, 256 B, 32 clients |
+| Concurrent clients | 8/64 clients | Batch 1, target 1,000/s, 256 B; 32-client baseline above |
+| PostgreSQL outage | Stop requested at 3s; start at 8s | 15-second target of 500/s, batch 100 |
+| Worker restart | KILL requested at 3s; start at 5s | Same 15-second target of 500/s |
+| Outbox with broker outage | 100 saved application events; broker stopped for 8s after stop completion | Failed attempt lasts more than 5s; a new dispatcher sends the original UUIDs |
+
+HTTP load cases run for ten seconds after two seconds of warm-up. SQL observation
+aims for a query every 50 ms and allows 30 seconds to finish observing outstanding
+events. Large payloads use batch 10 to fit the 1 MiB request limit. The study fixes
+the API request limit at 10,000/s, info logging, broker allocation at one core/1 GiB,
+and topic retention at seven days. Actual process flags, topic/database settings
+and verified HTTPS protocol are captured. Environment variables cannot silently
+retune a matched case.
+
+Inputs are varied ASCII JSON at the exact requested byte size, generated
+reproducibly from the recorded seed and namespace. The namespace separates one
+run's event IDs from another's. Duplicate submissions keep the same IDs and bytes.
+
+For the database comparison, input generation, table reset, warm-up and content
+checks happen outside the write timer. Single INSERT commits every row; batch
+INSERT and the independent COPY/staging/merge method commit every batch. They
+use the same indexed table and keep the first stored content for a repeated ID.
+Submitted events/s includes repeats; unique inserted rows/s counts only new rows.
+
+## Read the counts before the rate
+
+An offered rate is what the driver tried to schedule. Attempted events are what
+it actually sent. Acknowledged events have a successful matching HTTP response.
+Verified stored events are the unique rows found by the independent final check.
+A sending schedule the client missed is not a record the collector lost.
+
+| Measure | What is sampled or counted |
+| --- | --- |
+| HTTP ACK latency | One sample for each successfully acknowledged request |
+| SQL visibility upper bound | One sample for each event first observed after commit, from API receipt through completed SQL observation; includes polling/query delay |
+| In-window ACK rate | Responses finished within the target window, divided by that window |
+| Verified stored rate | Unique verified rows divided by the window, unfinished requests, observation and final verification together |
+
+`ObservedEvents` counts events with latency samples. `VerificationNS` records
+final-check time. A row found only at the final check gets no invented latency.
+The observer tracks unseen IDs in a temporary table on its own connection, so
+out-of-order commits remain observable. The final check independently compares
+IDs, types, times and payloads, and touches only that run's namespace/IDs. It
+never truncates a shared table or cleans another run's rows.
+
+A `limited` result keeps missed schedules, late starts, request/ACK tails,
+rejections, uncertain delivery, delayed polls and observer outages visible.
+A response just outside a finite window does not establish saturation. An
+uncertain ID absent at the final deadline stays unknown; absence then does not
+prove it can never arrive later. Missing acknowledged IDs, unexpected content/IDs
+or duplicate physical rows fail correctness and cannot become a speed result.
+
+p50/p95/p99 use the nearest-rank calculation on their separate raw samples.
+For example, p95 describes the time by which 95% of those samples finished.
+Receipt and SQL observation use the deployment clock; the host schedules load
+with monotonic time. Reports include query/poll time and the largest observation
+gaps. Only the deliberate PostgreSQL-outage experiment reconnects the observer
+and rebuilds its unseen-ID list, while recording the SQL gap. It does not infer
+commit times during the gap. Fault times record control requests/completions;
+starting a container is not proof that processing has recovered. Recovery cases
+are separate from capacity measurements.
+
+## Find the files behind a result
| Artifact | Contents |
| --- | --- |
-| `index.json`, `summary.csv` | Every configuration, status, summaries, attempts, raw references and checksums |
-| `manifest-N.json` | Immutable source SHA/fingerprint, host/VM, runtime settings, exact image IDs/digests |
-| `raw/-attempt-N.json.gz` | Every repetition/method, raw samples/backlog and ID-population evidence |
-| `resources-N.json.gz` | Coarse owned-container snapshots; not proof of a bottleneck |
-| `journal.json` | Atomic progress, compatibility identity and retained interrupted history |
-
-Gzip timestamps are zero; references include SHA256 and raw/compressed sizes.
-Per-capture limits are 128 MiB raw/64 MiB compressed. Pipeline populations use compact
-submission indices plus namespace/seed/count; outbox UUIDs are explicit. Credentials,
-CA files and private Docker/error evidence remain in ignored owned run directories.
-
-A partial case reruns all three repetitions on a fresh owned stack, retaining
-history and completed artifact bytes. Resume rejects changed source/files, seed,
-registry controls, runtime/host controls or image content/configuration. Exact image
-IDs remain in manifests; compatibility excludes only Compose's per-project image
-label, proven to alter config IDs without changing filesystem/execution. Other
-config and layers remain fingerprinted. Source/config changes need a new study.
-
-Interrupt with Ctrl-C/SIGTERM for bounded owned cleanup. A hard host/process kill
-can leave resources: inspect that run's private evidence and clean only that
-project. Never use global prune or measure over an abandoned owned stack.
-
-## Other entry points
-
-`make bench-db` and `make bench-pipeline` retain configurable single-run experiments
-on development HTTP. Their `BENCH_FLAGS` include count/batch/payload/duplicates or
-rate/duration/concurrency/pattern as appropriate; inspect `go run ./cmd/bench -h`.
-They are not the registered HTTPS deployment comparison. All single-run measurements
-still require committed source and own their stacks. Registered study mode rejects
-ad-hoc workload flags rather than silently changing the comparison.
-
-See [figure sources](../docs/figures/README.md) for charts generated from the audited
-index. [Historical local captures](results/local-2026-11-03/README.md) retain their
-fsync-bypass erratum: topic write caching was disabled while development mode
-still bypassed process-level fsync. They do not establish corrected deployment
-throughput. The new studies inspect and reject that bypass; old raw bytes remain
-unchanged. None of these local captures establishes maximum capacity, cloud cost,
-production adoption or tolerance of the only disk/host failing.
+| `index.json`, `summary.csv` | All configurations, statuses, summaries, attempts and raw-file checksums |
+| `manifest-N.json` | Source commit/fingerprint, host/VM, runtime settings and exact image IDs/digests |
+| `raw/-attempt-N.json.gz` | All methods/runs, raw timing, queue observations and ID sets |
+| `resources-N.json.gz` | Coarse snapshots of this run's containers; these do not establish a bottleneck |
+| `journal.json` | Progress, compatibility identity and the history of interrupted attempts |
+
+Each file reference includes SHA256 and raw/compressed sizes. Gzip timestamps
+are zero. A capture is limited to 128 MiB raw and 64 MiB compressed. HTTP ID sets
+use compact submission indices with namespace/seed/count; outbox UUIDs are stored
+explicitly. Private credentials, CA files and Docker/error logs remain in the
+ignored run directory.
+
+## Resume the same experiment
+
+Resume keeps completed captures unchanged. A partially completed case runs all
+three repetitions again on a fresh isolated stack and keeps its interrupted
+history. It rejects a changed source/file set, seed, case controls, host/runtime
+controls or image content/configuration. Exact image IDs remain in the manifests.
+Compatibility ignores only Compose's project-specific image label, which changed
+config IDs without changing filesystem or execution; other configuration/layers
+remain part of the fingerprint. Source or configuration changes need a new study.
+
+Ctrl-C/SIGTERM allows bounded cleanup of that run's resources. An uncatchable
+process or host kill can leave them behind. Inspect the private evidence and
+remove only that project; do not use global prune or benchmark over an abandoned
+stack.
+
+## Other commands and figures
+
+`make bench-db` and `make bench-pipeline` run configurable single experiments
+on development HTTP. `BENCH_FLAGS` controls count/batch/payload/duplicates or
+rate/duration/concurrency/pattern; see `go run ./cmd/bench -h`. They still need
+committed source and create their own stacks. They are separate from the registered
+HTTPS study, which rejects ad-hoc workload flags.
+
+The [figure guide](../docs/figures/README.md) explains the questions behind each
+plot and how to regenerate it from the audited index. [Historical captures](results/local-2026-11-03/README.md)
+retain a correction: topic write caching was off, but development mode still
+bypassed process-level fsync. Their old raw bytes remain unchanged. The corrected
+studies inspect and reject that bypass. No local capture here establishes maximum
+capacity, cloud cost, production adoption or recovery from losing the only host/disk.
diff --git a/benchmarks/results/local-2026-11-03/README.md b/benchmarks/results/local-2026-11-03/README.md
index 8f2549b..e11482e 100644
--- a/benchmarks/results/local-2026-11-03/README.md
+++ b/benchmarks/results/local-2026-11-03/README.md
@@ -1,22 +1,23 @@
-# Local experiments — 3 November 2026
+# Historical local experiments (3 November 2026)
-**Correction discovered during the self-hosting audit:** these pipeline samples
-used Redpanda's dev-container mode, which started the pinned v26.2.6 broker with
-`--unsafe-bypass-fsync=true`. Turning off topic write caching did not remove this
-process-level flag ([startup mode reference](https://docs.redpanda.com/streaming/current/reference/rpk/rpk-redpanda/rpk-redpanda-start/)). The raw captures are preserved, but their pipeline timings
-must be read as development-mode measurements. They do not establish broker-
-fsync-enabled throughput or deployment sizing. The current configuration is
-corrected and replacement measurements are pending. The PostgreSQL-only write
-comparison retains its recorded PostgreSQL fsync/synchronous_commit settings.
+These pipeline runs used Redpanda's dev-container mode. It started v26.2.6
+with `--unsafe-bypass-fsync=true`, even though topic write caching was off.
+The [startup-mode reference](https://docs.redpanda.com/streaming/current/reference/rpk/rpk-redpanda/rpk-redpanda-start/)
+explains the separate process flag. Their timings describe that development setup
+and cannot establish fsync-enabled broker throughput or deployment sizing.
+The [replacement self-hosted study](../selfhost-2026-11-04/README.md) uses the
+corrected configuration. These old raw captures stay unchanged. The PostgreSQL-only
+comparison still has its recorded fsync/synchronous_commit settings.
-Measured source: [deefc8162504fa482c19c63edda05c1c1a4c2ae7](https://github.com/feat7/ingestkit/tree/deefc8162504fa482c19c63edda05c1c1a4c2ae7). All four manifests record clean source at this revision. Subsequent validation/lifecycle fixes are regression-tested but these timing captures have not been rerun on those later revisions. This branch must be pushed before that GitHub revision link resolves; the commit is available locally now.
+
+Measured source: [deefc8162504fa482c19c63edda05c1c1a4c2ae7](https://github.com/feat7/ingestkit/tree/deefc8162504fa482c19c63edda05c1c1a4c2ae7). All four manifests record clean source at this revision. Subsequent validation/lifecycle fixes are regression-tested but these timing captures have not been rerun on those later revisions. The recorded revision identifies the implementation used for these samples.
Apple M1 Max, 10 logical CPUs, 64 GiB physical memory; OrbStack Docker VM with 10 CPUs and about 15.7 GiB reported memory. Go generator 1.26.5; container builds 1.26.10. PostgreSQL 18.6, Redpanda 26.2.6, one broker/replica, event topic three partitions, one consumer. PostgreSQL fsync/synchronous_commit/full_page_writes were on; topic write.caching was false, retention seven days. Exact versions, image hashes, indexes and topic settings are in each manifest. Host, generator, observer and services share resources. The manifest's generic caveat says “Docker Desktop”; its actual runtime fields identify OrbStack. The numbers below describe this local VM.
## Database methods
-10,000 submissions, 256-byte JSON payloads, configured batch size 100, one complete batch of warm-up per method, three measured repetitions with rotated method order. Every repetition verified exact IDs, types, timestamps and JSON payloads. No generation, reset or verification inside the timer. Single INSERT commits every row; batch INSERT and COPY/stage/merge commit every batch. The COPY case calls the service's actual store.
+10,000 submissions, 256-byte JSON payloads, configured batch size 100, one complete batch of warm-up per method, three measured repetitions with rotated method order. Every repetition verified exact IDs, types, timestamps and JSON payloads. No generation, reset or verification inside the timer. Single INSERT commits every row; batch INSERT and COPY/stage/merge commit every batch. At that recorded revision, the COPY case calls the service's store.
| Method | No duplicates: median seconds | Submitted/s | 10% duplicates: median seconds | Submitted/s |
| --- | ---: | ---: | ---: | ---: |
@@ -30,6 +31,9 @@ The duplicate workload submitted 10,000 and inserted 9,000 distinct events each
## Whole pipeline
+p95 is the time by which 95% of the relevant samples finished. HTTP timing
+samples successful requests; storage timing samples observed events.
+
Each configuration: two-second warm-up, three ten-second measured windows, 10,000 unique events/window, 256-byte payload, HTTP batches of 100, eight workers. Steady offers 1,000 events/s throughout; burst offers the same count at 4,000 events/s during the first 2.5 seconds, then remains idle for the rest of the window. No retries in the load driver.
| Pattern / repetition | Accepted / stored | Missed / ambiguous / rejected | Stored/s including completion | HTTP ACK p95 ms | Storage visibility p95 ms |
@@ -43,11 +47,11 @@ Each configuration: two-second warm-up, three ten-second measured windows, 10,00
[Steady raw JSON](steady/pipeline.json), [CSV](steady/pipeline.csv), [environment](steady/manifest.json), [resource snapshots](steady/resources.json). [Burst raw JSON](burst/pipeline.json), [CSV](burst/pipeline.csv), [environment](burst/manifest.json), [resource snapshots](burst/resources.json).
-Every accepted ID set matched the stored set, checked before cleanup. Sorted unique ID hashes are saved alongside deterministic seeds; raw UUID arrays are omitted to keep the captures bounded. All latency samples are retained. No late schedules or queue misses were recorded. There were no accepted IDs still pending at the ten-second boundary; the final SQL confirmation adds approximately 41–55ms to the complete interval. The coarse sampled accepted-minus-visible peak was 881 in burst repetition 1, versus 36 and 100 in repetitions 2 and 3. This is an observation backlog, not an exact Kafka offset-lag measurement. The cause of the first burst's latency variation is not established; these three repetitions are insufficient for a general latency guarantee.
+Before cleanup, every acknowledged ID was checked against the IDs stored in PostgreSQL; the sets matched. Sorted unique ID hashes are saved alongside deterministic seeds; raw UUID arrays are omitted to keep the captures bounded. All latency samples are retained. No late schedules or queue misses were recorded. There were no accepted IDs still pending at the ten-second boundary; the final SQL confirmation adds approximately 41–55ms to the complete interval. The coarse sampled accepted-minus-visible peak was 881 in burst repetition 1, versus 36 and 100 in repetitions 2 and 3. This counts acknowledged events that the SQL observer had not yet seen. It does not measure the exact number of unread queue records. The cause of the first burst's latency variation is not established; these three repetitions are insufficient for a general latency guarantee.
HTTP ACK latency is per successful request, including client encoding/network and broker acknowledgement. Storage latency is per event, from API receipt to the end of the first SQL query that sees the committed row. It includes 50ms polling plus query time and is an upper bound, not the physical commit instant. Persisted/s uses the complete ten-second window plus request tail and final confirmation, so burst's idle time is included. It does not describe the active burst's processing capacity.
-These are verified offered-load experiments, **not maximum-capacity measurements**. Resource samples do not isolate the bottleneck. There is no cost/server sizing result, sustained saturation test, long-duration stability result or host/disk-loss experiment here. All four status files report successful scoped resource destruction. Recovery experiments are separate integration tests, not throughput samples.
+These experiments check a chosen sending rate and its saved events. They do not establish maximum capacity. Resource samples do not isolate the bottleneck. There is no cost/server sizing result, sustained saturation test, long-duration stability result or host/disk-loss experiment here. All four status files report successful scoped resource destruction. Recovery experiments are separate integration tests, not throughput samples.
## Reproduce
diff --git a/benchmarks/results/selfhost-2026-11-04/README.md b/benchmarks/results/selfhost-2026-11-04/README.md
index 6e9e0aa..c81841a 100644
--- a/benchmarks/results/selfhost-2026-11-04/README.md
+++ b/benchmarks/results/selfhost-2026-11-04/README.md
@@ -1,16 +1,32 @@
-# Corrected self-hosted ingestion study
+# Results with the batch-INSERT writer
-Measured 4 November 2026 from clean source `213e4cc50523882f0d0cf7533d064494387d3207`. The deployed consumer uses atomic **batch INSERT**. The explicit COPY/staging/merge reference remains independently implemented in the database comparison. The [complete earlier COPY-writer study](../selfhost-copy-2026-11-04/README.md) motivated that change; its bytes and limits are retained.
+Measured on 4 November 2026 from clean source `213e4cc50523882f0d0cf7533d064494387d3207`.
+The deployed worker uses atomic batch INSERT. The database comparison still has
+an independent COPY/staging/merge implementation. The [earlier complete study](../selfhost-copy-2026-11-04/README.md)
+led to the writer change; its captures and limits remain unchanged.
-## What this capture establishes
+## What was checked
-All 25 registered configurations completed with three measured repetitions: 99 database method/repetition rows, 33 HTTPS load windows and 9 recovery repetitions. Nine configurations contain reported limits. Every broker-acknowledged ID reconciled with independently verified stored content; no accepted missing IDs, unexpected IDs or duplicate physical rows were found. Ambiguous HTTP outcomes are a separate population and are **not** counted as successful delivery.
+All 25 cases completed with three measured runs each: 99 database method/run
+rows, 33 HTTPS load windows and 9 recovery runs. Nine cases report limits. Every
+ID acknowledged by the queue was found with its expected content in the independent
+storage check. There were no missing acknowledged IDs, unexpected IDs or duplicate
+physical rows. Requests with uncertain outcomes are counted separately and never
+become successful deliveries in the report.
-The independent [auditor](../../audit_study.py) verified registry controls, method/repetition counts, immutable artifact hashes and bounds, raw timing populations, nearest-rank p50/p95/p99, actual request/ACK windows, ID sets, rates, summaries, broker/topic/PostgreSQL durability and the trusted HTTPS route. An exact scan against this owned run’s generated credentials passed.
+The [independent auditor](../../audit_study.py) checked registered settings,
+method/run counts, file checksums and size limits, raw timing samples, nearest-rank
+p50/p95/p99, request/ACK windows, ID sets, rates, summaries, broker/topic/PostgreSQL
+durability settings and trusted HTTPS routing. A scan for this run's exact generated
+credentials found none in the published captures.
-## Database comparison
+## Which database write was faster?
-5,000 submissions per method/repetition, rotated method order, varied deterministic JSON payloads. Generation, warm-up, reset and exact verification are outside elapsed time. Single INSERT commits each row; batch INSERT and COPY/stage/merge commit each batch against the same indexed table and first-content conflict policy. Values below are **median seconds [min–max] across all three repetitions**.
+Each method submitted 5,000 varied, reproducible JSON events per run. Method order
+rotated. Generation, reset, warm-up and exact verification happened outside the
+write timer. Single INSERT committed each row; batch INSERT and COPY/stage/merge
+committed each batch to the same indexed table, preserving the first stored content
+for repeated IDs. Each cell is median seconds followed by the range of all three runs.
| Case | Single INSERT | Batch INSERT | COPY + merge |
| --- | ---: | ---: | ---: |
@@ -26,13 +42,26 @@ The independent [auditor](../../audit_study.py) verified registry controls, meth
| db-duplicates-50 | 4.253 [3.998–4.346] | 0.096 [0.091–0.198] | 0.263 [0.253–0.509] |
| db-duplicates-90 | 1.394 [1.198–2.531] | 0.064 [0.056–0.080] | 0.229 [0.219–0.423] |
-Batch INSERT had the lower median than COPY/staging/merge in all eleven configurations in both studies. Individual repetitions overlap or reverse that ordering in some larger-batch/payload cases. This supports the simpler default here, not a universal COPY threshold. No adaptive cutoff, UNNEST comparison or typed-schema speed claim is inferred. Duplicate configurations insert fewer unique rows; submitted/s differs from unique inserted/s.
+Batch INSERT had a lower median than COPY/staging/merge in all eleven cases in
+both studies. Some individual runs overlapped or reversed that order, particularly
+with larger batches/payloads. The result supports the simpler writer for this
+workload. It establishes no universal COPY threshold, adaptive cutoff, UNNEST
+comparison or typed-schema speed advantage. Duplicate cases write fewer new rows;
+submitted/s therefore differs from unique inserted/s.
-## HTTPS pipeline
+## What reached storage over HTTPS?
-Ten-second windows after two-second warm-up; 50 ms target SQL polling; bounded 30-second observation drain; private-CA HTTPS with certificate verification. Default controls: 1,000 offered events/s, batch100, 32 clients, 256B varied payload. Larger payloads use batch10, with the 256B/batch10 case as their matched control. Burst offers the same total in the first quarter of the window.
+The load window was ten seconds after two seconds of warm-up. SQL polling aimed
+for every 50 ms, with a bounded 30-second observation period afterward. HTTPS used
+a verified private CA. Defaults were a target of 1,000 events/s, batches of 100,
+32 clients and varied 256-byte payloads. Larger payloads used batch 10 with the
+256-byte/batch-10 case as their control. The burst sent the same total in the
+first quarter of the window.
-Counts are per repetition in order1/2/3. ACK p95 is per successful HTTP request; SQL p95 is API receipt to first observed committed row per observed event, including polling/query delay. The two latency populations differ.
+Read counts in run order 1/2/3. ACK p95 samples successful HTTP requests. SQL p95
+samples observed events from API receipt until the first completed query that
+sees their committed row, including polling/query delay. These are different
+sample sets. p95 is the time by which 95% of the relevant samples finished.
| Case | Attempted | Broker acknowledged | Verified stored | ACK p95 ms | SQL p95 upper bound ms |
| --- | --- | --- | --- | --- | --- |
@@ -48,15 +77,28 @@ Counts are per repetition in order1/2/3. ACK p95 is per successful HTTP request;
| pipeline-concurrency-8 | 4680 / 4644 / 4492 | 4680 / 4644 / 4492 | 4680 / 4644 / 4492 | 20.81 / 20.87 / 22.24 | 72.65 / 71.46 / 90.68 |
| pipeline-concurrency-64 | 10000 / 10000 / 9938 | 10000 / 10000 / 9938 | 10000 / 10000 / 9938 | 19.58 / 21.20 / 37.42 | 86.18 / 109.43 / 225.58 |
-The batch100 baseline, 100/s case and first-quarter burst completed without reported limits. Other cases retain generator misses, late schedules, request/ACK tails, observer delays or ambiguous delivery. A finite-window tail is not by itself evidence of saturation. Lower attempted counts mean the driver did not generate the target; they do not mean the collector lost those unattempted events.
+The batch-100 baseline, 100/s case and burst finished without reported limits.
+Other cases retain missed sending schedules, late requests/responses, observer
+delays or uncertain delivery. A response outside the window alone does not show
+saturation. Lower attempted counts mean the driver did not send its full target;
+the collector cannot lose an event that was never submitted.
-At 10,000 offered events/s, repetition2 retained 1,000 ambiguous IDs absent at its final deadline. The 16KiB case’s repetition2 retained 160 such IDs. Absence at that deadline means delivery remains unknown, not proved never delivered. Reuse those IDs on retry. No ambiguous ID is converted into an acknowledgement or a fabricated latency sample.
+At a target of 10,000 events/s, run 2 left 1,000 uncertain IDs absent at the final
+check. The 16 KiB case left 160 such IDs in run 2. Delivery remains unknown at that
+deadline; it is not proved impossible later. Retry the same IDs. They contribute
+neither an acknowledgement nor an invented latency sample.
-In-window ACK rate divides only acknowledgements completed inside the target window by that window. Stored rate divides independently verified rows by the full window, request tail, observation drain and final independent verification. A final census can find a row without yielding a pending-observer latency sample; `ObservedEvents` and `VerificationNS` expose the distinction. Inspect all rate denominators and limit reasons in [index.json](index.json). No maximum capacity or cloud-cost claim follows.
+In-window ACK rate counts only responses completed in the target window. Stored
+rate divides verified rows by the full window, unfinished requests, observation
+and final verification. Rows found only in the final query may have no observation
+latency sample; `ObservedEvents` and `VerificationNS` make that distinction visible.
+[index.json](index.json) records the denominators and each limit. These runs do not
+establish maximum capacity or cloud cost.
-## Availability experiments
+## Did events survive the outages?
-Each row below represents three repetitions, separate from throughput claims. Actual fault request/completion timestamps are retained in raw captures.
+Each experiment ran three times. Raw captures retain the actual fault request
+and completion times.
| Experiment | Controls | Verified outcome |
| --- | --- | --- |
@@ -64,13 +106,27 @@ Each row below represents three repetitions, separate from throughput claims. Ac
| Consumer | KILL requested at3s; restart requested at5s during the same workload | Every accepted ID/content reconciled after group recovery; actual Docker timings retained |
| Outbox + broker | 100 persisted application events; broker stopped for8s after stop completion; failed attempt exceeds5s | Pending IDs survived a new dispatcher; replay yielded100 accepted/stored unique IDs each repetition |
-These availability results do not prove an arbitrary kill landed inside the SQL-commit/offset window. The separate deterministic process-kill regression pauses exactly there, verifies an uncommitted offset, and replays to one stored row. SQL gaps cannot reveal precise commit times. Docker stop/start completion is a control observation, not an exact service-availability clock.
+The exact SQL-commit/offset crash test is separate: it pauses after SQL commits,
+checks that the queue position is still unsaved, then restarts and verifies one
+row after replay. An arbitrary restart would not prove it hit that gap. SQL
+observation gaps cannot reveal precise commit times, and Docker stop/start
+completion is a control timestamp rather than an exact availability transition.
-## Environment and reproducibility
+## Environment and reproduction
-[manifest-1.json](manifest-1.json) records actual versions/image IDs/digests, running broker process controls, source/host/VM metadata, topic configuration, database durability/indexes and trusted TLS protocol. Broker1core/1GiB, one replica, seven-day log retention; process fsync bypass false and topic write caching false. PostgreSQL18.6 fsync, synchronous commit and full-page writes on. API limit10,000 requests/s, info logging. Local TLS trust was verified; public ACME issuance was not tested.
+[manifest-1.json](manifest-1.json) records versions, image IDs/digests, actual
+broker process settings, host/VM, topics, database durability/indexes and verified
+TLS. The broker had one core, 1 GiB, one replica and seven-day retention, with
+process fsync bypass and topic write caching both false. PostgreSQL 18.6 had fsync,
+synchronous commit and full-page writes on. The API limit was 10,000 requests/s
+with info logging. Local HTTPS trust was tested; public ACME issuance was not.
-The M1 Max physical host had10 logical CPUs/68,719,476,736 bytes RAM; OrbStack’s Linux Docker VM exposed10 CPUs/16,818,991,104 bytes RAM. The generator and SQL observer ran on that same physical host alongside existing workloads. Only owned containers were controlled. Resource snapshots are coarse observations, not a calibrated bottleneck or isolated-disk benchmark. One broker/host does not protect against host/disk loss or retention expiry.
+The M1 Max host had 10 logical CPUs and 68,719,476,736 bytes RAM. Its OrbStack
+Linux Docker VM exposed 10 CPUs and 16,818,991,104 bytes RAM. The generator and
+SQL observer shared the physical host with existing workloads. Only this run's
+containers were controlled. Coarse resource snapshots do not isolate a bottleneck
+or measure disk performance. One broker/host does not protect against disk loss,
+host loss or retention expiry.
Run from the repository root:
@@ -80,6 +136,14 @@ python3 benchmarks/audit_study.py benchmarks/results/selfhost-2026-11-04
make bench-study STUDY_FLAGS='-out benchmarks/results/my-study -seed 42'
~~~
-See the [study guide](../../README.md) for controls, prerequisites, resume and artifact bounds. The current source can audit these immutable captures; reproducing the exact measured implementation requires the recorded source revision. Changes to docs/evidence after that revision do not retroactively remeasure it.
-
-[index.json](index.json) contains readable controls, summaries, statuses and SHA256 references; [summary.csv](summary.csv) lists every case. [journal.json](journal.json) retains progress/attempts. Raw gzip files under `raw/` have zero timestamps and include all repetitions, request/event timing samples, backlog observations and compact ID populations. Metadata and coarse resources are independently checksummed. Private keys/config/CA/logs remain in the ignored owned run directory. No failed/limited case was discarded.
+The [experiment guide](../../README.md) covers prerequisites, controls, resume
+and file limits. Current source can audit these captures. Repeating the exact
+measured implementation requires its recorded revision; later documentation or
+evidence changes do not remeasure it.
+
+Use [index.json](index.json) for controls, results, statuses and SHA256 references;
+[summary.csv](summary.csv) lists every case and [journal.json](journal.json) keeps
+attempt history. Raw gzip files in `raw/` have zero timestamps and contain all
+runs, timing samples, backlog observations and compact ID sets. Metadata and
+coarse resources have independent checksums. Private keys/config/CA/logs stay in
+the ignored run directory. Failed or limited cases were not discarded.
diff --git a/benchmarks/results/selfhost-copy-2026-11-04/README.md b/benchmarks/results/selfhost-copy-2026-11-04/README.md
index 90c9d83..dd52aa1 100644
--- a/benchmarks/results/selfhost-copy-2026-11-04/README.md
+++ b/benchmarks/results/selfhost-copy-2026-11-04/README.md
@@ -1,33 +1,32 @@
-# COPY-writer reference study
+# Results with the original COPY writer
-Completed 4 November 2026 from clean source `dccf4b3`. This is the first corrected
-self-hosted HTTPS study, before the evidence-driven switch of the deployed writer
-to batch INSERT. Keep these captures as a reference; the final writer study is
-[recorded separately](../selfhost-2026-11-04/README.md).
+This complete study ran on 4 November 2026 from clean source `dccf4b3`, before
+the deployed worker changed to batch INSERT. It uses the corrected HTTPS
+self-hosted setup. The [second study](../selfhost-2026-11-04/README.md) measures
+the changed writer. Keep this first capture as the comparison that led to it.
-All 25 registered cases completed: 99 database method/repetition rows, 33 pipeline
-windows and 9 recovery repetitions. Nine cases are explicitly limited. Independent
-Python checks reconciled raw samples, nearest-rank percentiles, request/ID
-populations, rates, summaries, immutable checksums, registered controls and runtime
-durability/HTTPS settings. An exact scan against this owned run’s generated
-credentials passed. Each case uses three measured repetitions; all accepted event
-IDs reconciled with independently verified content. Limits are retained in index
-and raw captures and do not establish maximum capacity.
+All 25 cases completed with three measured runs each: 99 database method/run
+rows, 33 HTTP load windows and 9 recovery runs. Nine cases report limits. Every
+acknowledged event ID was found with its expected stored content. Independent
+Python checks verified raw samples, nearest-rank percentiles, request/ID sets,
+rates, summaries, checksums, case controls, durability settings and HTTPS. A scan
+for the run's exact generated credentials found none in the captures. All limits
+remain in the index and raw files; these are not maximum-capacity measurements.
-Batch INSERT had the lower median elapsed time than COPY/staging/merge in all
-11 database configurations. This motivates the separate writer change and new
-measurements; it does not make a universal claim about PostgreSQL COPY.
+Batch INSERT had a lower median elapsed time than COPY/staging/merge in all 11
+database configurations. That result led to a separate writer change and a new
+full study. It does not establish a general ranking of PostgreSQL COPY.
-Source and actual image/runtime/host controls are in [manifest-1.json](manifest-1.json).
-The generator and SQL observer shared an M1 Max physical host with the Docker VM
-and existing workloads. Only owned containers were controlled. PostgreSQL fsync
-and synchronous commit were on; the broker’s process bypass was false and topic
-write caching was false. One broker/replica is not protection from host/disk loss.
-Local private-CA HTTPS was verified; public certificate issuance was not tested.
+[manifest-1.json](manifest-1.json) records source, images, runtime and host settings.
+The sender and SQL observer shared an M1 Max host with its Docker VM and other
+workloads; only this run's containers were controlled. PostgreSQL fsync and
+synchronous commit were on. The broker's process bypass and topic write caching
+were false. A single broker replica does not recover data lost with the only host
+or disk. Private-CA HTTPS was verified; public certificate issuance was not tested.
-Read [index.json](index.json) for all case controls, summaries, limits and raw
-artifact references, [summary.csv](summary.csv) for the case listing, and
-[journal.json](journal.json) for progress history. Run `python3
+[index.json](index.json) contains all settings, summaries, limits and raw-file
+references. [summary.csv](summary.csv) lists the cases; [journal.json](journal.json)
+records progress. Run `python3
benchmarks/audit_study.py benchmarks/results/selfhost-copy-2026-11-04` from the
-repository root for a read-only independent audit. Raw gzip files have zero
-timestamps and SHA-256 references; no failed/limited cases were discarded.
+repository root for an independent read-only audit. Raw gzip timestamps are zero
+and files have SHA-256 references. No failed or limited case was discarded.
diff --git a/deploy/README.md b/deploy/README.md
index a819afa..f9e8e67 100644
--- a/deploy/README.md
+++ b/deploy/README.md
@@ -1,38 +1,27 @@
-# Self-hosted deployment
+# Run IngestKit on one server
-Prepare private configuration for the hostname you will use:
+This Compose deployment runs Caddy, the Go API, Redpanda, the database worker and
+PostgreSQL on one Linux host. Caddy exposes HTTPS; the other services have no
+public ports. Docker builds the Go programs for you.
-~~~sh
-deploy/configure.sh events.example.com
-~~~
+## Prepare the host
-The script requires a POSIX shell, standard system utilities and OpenSSL. It
-creates deploy/.env with mode 0600, three independent secrets and an initial API
-key mapped to tenant default. It does not install software or contact a server.
-Existing configuration is preserved; re-running against the same path fails.
-Keep the file private and out of source control. API_KEYS is a JSON object;
-duplicate decoded key names are rejected, including escaped spellings of the
-same key. Use distinct keys for overlap rotation.
+Install Git, Docker Engine with Compose v2.24.4+, OpenSSL and curl. Point a
+hostname you own at the server, and make ports 80 and 443 reachable. Replace
+`events.example.com` in every command with that hostname. Caddy uses DNS and
+those ports to obtain the public certificate, then keeps it in a named volume.
+Local automated tests use a private certificate authority; they do not test
+public certificate issuance.
-An optional second argument selects a configuration directory. localhost is
-accepted for local TLS verification. Public deployment will require a hostname
-pointing to the host and reachable gateway ports 80/443.
+Allow memory for Redpanda's 1 GiB allocation plus PostgreSQL, Go and Docker.
+The [measured environment](../benchmarks/results/selfhost-2026-11-04/manifest-1.json)
+had a Docker VM with 10 CPUs and about 16 GiB RAM; that is not a minimum sizing
+recommendation. Disk use depends on traffic and retention. Both the queue and
+database live on this host, so losing its disk can lose both.
-## Start on a server
+## Create private settings and start
-Replace `events.example.com` with your own DNS hostname in every command.
-
-Use a Linux host with Git, Docker Engine and Docker Compose v2.24.4 or newer,
-OpenSSL, and curl. Allow room for the broker's 1 GiB allocation plus PostgreSQL,
-the Go services and Docker. The [measured environment](../benchmarks/results/selfhost-2026-11-04/manifest-1.json)
-used a Docker VM exposing 10 CPUs and about 16 GiB RAM; it does not establish a minimum host size.
-Disk requirements depend on traffic and retention. This is a single-host setup:
-losing its disk can lose both queued and stored events.
-
-Point the hostname's DNS records at the host. Ports 80 and 443 must be reachable
-for Caddy's certificate issuance and HTTPS traffic. Caddy keeps its certificates
-in a named volume. Public certificate issuance requires working DNS and external
-reachability; the automated local test uses a private CA instead.
+Run this once from a fresh checkout:
~~~sh
git clone https://github.com/feat7/ingestkit.git
@@ -42,14 +31,24 @@ docker compose --env-file deploy/.env -f deploy/compose.yml config --quiet
docker compose --env-file deploy/.env -f deploy/compose.yml up -d --build --wait
~~~
-Only the gateway publishes ports. PostgreSQL, Kafka, broker administration and
-service metrics stay on Docker's private network. The consumer uses an
-`ingestkit_writer` login with schema usage, SELECT and INSERT (no temporary-table privilege);
-migrations use the separate admin login.
+The configuration script needs a POSIX shell, standard utilities and OpenSSL.
+It creates deploy/.env with file mode 0600, three independent secrets and an API
+key mapped to tenant default. It neither contacts the server nor installs software.
+It refuses to overwrite an existing configuration, so keep that file private,
+out of Git and backed up.
+
+An optional second argument to the script chooses another configuration directory.
+The hostname localhost is accepted for local TLS verification. API_KEYS is a
+JSON object; repeated key names are rejected even if an escaped spelling decodes
+to the same key. To rotate a key, use two distinct keys for the same tenant.
-## Send and verify
+The database, broker, administration and metrics stay on Docker's private network.
+The consumer login `ingestkit_writer` has schema usage, SELECT and INSERT, without
+temporary-table privileges. Migrations run with a separate admin login.
-For the initial generated mapping, load the API key locally without printing it:
+## Send the checkout events and find their rows
+
+For the initially generated key mapping, load the key without printing it:
~~~sh
INGESTKIT_API_KEY=$(sed -n 's/^API_KEYS={"\([0-9a-f]*\)":"default"}/\1/p' deploy/.env)
@@ -64,12 +63,12 @@ docker compose --env-file deploy/.env -f deploy/compose.yml exec -T postgres \
"SELECT tenant_id,event_id,event_type,persisted_at FROM ingestkit.events ORDER BY persisted_at DESC LIMIT 10;"
~~~
-HTTP 202 acknowledges the broker write. Storage happens asynchronously; allow
-time for the consumer before checking SQL. Repeating the same IDs stores one row
-per tenant and event ID. The first stored content wins. Use new UUIDs for new
-business events. The API key belongs in trusted backend code.
+A 202 response confirms the queue write. Give the background worker time to save
+the rows before checking SQL. Sending the fixture again keeps one row per tenant
+and event ID, with the first stored content unchanged. Use new UUIDs for new
+business events. Keep the key in your backend, where users cannot retrieve it.
-## Stop or update configuration
+## Stop services or reload settings
~~~sh
# Stop and remove containers; preserve all named data volumes.
@@ -79,19 +78,23 @@ docker compose --env-file deploy/.env -f deploy/compose.yml down
docker compose --env-file deploy/.env -f deploy/compose.yml up -d --build --wait
~~~
-A plain `restart` does not reload environment values. Never add `down -v` to an
-ordinary shutdown. Keep a private backup of deploy/.env as well as your database
-backups: changing PostgreSQL's initial admin password variable does not change
-the password inside an existing database.
-
-The pinned [Caddy official image](https://hub.docker.com/_/caddy) is
-`2.11.7-alpine`. Redpanda starts without dev-container mode, with a 1 GiB memory
-allocation, one core, overprovisioned scheduling and explicit
-`--unsafe-bypass-fsync=false`; both topics have `write.caching=false`. See the
-[Redpanda mode reference](https://docs.redpanda.com/streaming/current/reference/rpk/rpk-redpanda/rpk-redpanda-mode/)
-for why development defaults must be examined. PostgreSQL retains its normal
-fsync and synchronous commit settings. These settings do not provide replication
-or protection from losing this host.
-
-See [operating the collector](../docs/operations.md) for readiness, disk growth,
-key rotation, backup/restore and upgrade procedures.
+A plain `restart` keeps the old environment. Recreate affected containers after
+editing configuration. Ordinary shutdown preserves database, broker and certificate
+volumes; keep `down -v` out of that procedure.
+
+Back up deploy/.env separately from the database. PostgreSQL uses its initial
+admin password variable only when it creates the database directory; changing
+that variable does not change an existing login's password.
+
+## Disk durability settings
+
+The [Caddy image](https://hub.docker.com/_/caddy) is pinned to `2.11.7-alpine`.
+Redpanda starts outside dev-container mode, with one core, a 1 GiB allocation,
+overprovisioned scheduling and `--unsafe-bypass-fsync=false`. Both topics use
+`write.caching=false`. The [Redpanda mode reference](https://docs.redpanda.com/streaming/current/reference/rpk/rpk-redpanda/rpk-redpanda-mode/)
+explains why development defaults need checking. PostgreSQL keeps its normal
+fsync and synchronous-commit settings. None of these settings adds another copy
+of the host's disks.
+
+The [operator guide](../docs/operations.md) covers readiness, queue growth,
+key rotation, backups, fresh-target restore and upgrades.
diff --git a/docs/api.md b/docs/api.md
index 2933ec0..cc0e383 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -1,13 +1,14 @@
-# HTTP event contract
+# HTTP API
-Use the HTTPS URL from [deployment](../deploy/README.md). Authenticate every
-write with `Authorization: Bearer ` and send `Content-Type: application/json`.
-The server maps the key to a tenant; callers do not supply tenant identity. The
-deployment default token bucket refills at 10,000 **requests**/s per tenant,
-with a 10,000-request burst allowance. These are configuration limits, not
-measured capacity; batched events consume one request.
+Send JSON to the HTTPS URL from the [deployment guide](../deploy/README.md).
+Every write needs `Authorization: Bearer ` and
+`Content-Type: application/json`. The key selects the tenant, a name stored
+with each event so the same UUID can exist independently for different tenants.
+Callers do not send a tenant in the event body.
-`POST /v1/events` accepts one envelope:
+## Send one event or a batch
+
+`POST /v1/events` accepts one event envelope, the fields around your payload:
~~~json
{
@@ -18,25 +19,32 @@ measured capacity; batched events consume one request.
}
~~~
-`POST /v1/events/batch` accepts `{ "events": [ ... ] }`. Use stable UUIDs that
-were saved with the business operation. Create a new UUID for a new event, and
-reuse the same UUID and serialized content for an uncertain retry. The first
-stored event for `(tenant_id,event_id)` wins; a later payload does not update it.
-Unknown envelope fields, malformed JSON and values incompatible with PostgreSQL
-JSONB are rejected. Payloads must be objects. Event types are 1–128 bytes.
-Timestamps must parse as RFC 3339. See [delivery details](delivery.md) for edge cases.
+`POST /v1/events/batch` accepts `{ "events": [ ... ] }`.
+Save a UUID with the business operation and keep its content for retries.
+Use a new UUID for a new event. If a send times out, retry the saved UUID and
+content. The first stored `(tenant_id,event_id)` wins; sending new content for
+that key does not update it.
+
+The payload must be a JSON object. Event types are 1 to 128 bytes, and timestamps
+must parse as RFC 3339. The API rejects malformed JSON, unknown envelope fields
+and values PostgreSQL JSONB cannot store. [Delivery details](delivery.md) explain
+the Unicode, numeric and nesting restrictions.
| Limit | Value |
| --- | --- |
| Encoded individual input event | 256 KiB |
| HTTP request body | 1 MiB |
-| Events in a batch | 1–100 |
+| Events in a batch | 1 to 100 |
| Payload nesting | At most 64 levels |
-Large events may require smaller batches to fit the request limit. For example,
-ten 16 KiB payloads fit; one hundred do not.
+For large events, reduce the batch size to fit the whole request. Ten 16 KiB
+payloads fit the request limit; one hundred do not.
-## Responses and retries
+The deployment's request limiter adds 10,000 request tokens per second per tenant
+and permits a burst of 10,000 requests. A batch consumes one request token.
+Those settings limit requests; they do not establish measured event capacity.
+
+## Read the response before marking an event sent
A successful response is HTTP 202:
@@ -44,36 +52,38 @@ A successful response is HTTP 202:
{"status":"accepted","event_ids":["dc12060f-f3a6-4ed3-9ea9-2d396b260b41"],"request_id":"f8c22d85-5e93-4cb5-a456-18b0f104bcca"}
~~~
-The returned IDs match input order. This acknowledges the broker append. It does
-not wait for the consumer or PostgreSQL. A batch is not a transaction across HTTP,
-the broker and database. A timed-out/failed request may have delivered some or all
-records, so retry identical IDs and content rather than generating replacements.
+The IDs must match the input order. This confirms that the queue acknowledged
+the events. It does not wait for the database worker or PostgreSQL. An HTTP batch
+is not one transaction across all services. A failed or timed-out request can
+have delivered some or all records; retry the original IDs and content.
-| HTTP result | Caller action |
+| HTTP result | What to do |
| --- | --- |
-| 202 with matching IDs | Broker acknowledged; verify persistence separately when required |
-| 400 | Fix the invalid envelope; do not blindly retry |
-| 401 | Fix/rotate authentication; preserve unsent business events |
-| 404 or redirect | Correct the endpoint/configuration |
-| 413 | Reduce event/request size; split oversized batches |
-| 429 | Retry the same content with bounded backoff |
-| 500/502/503 or other server failure | Delivery may be uncertain; bounded retry with the same IDs |
-| Timeout, connection loss or invalid acknowledgement | Delivery uncertain; retain IDs and retry |
-| Untrusted TLS certificate | Fix trust/hostname; never disable verification |
-
-Application errors include `error`, `message`, `request_id` and `timestamp`;
-`X-Request-ID` is also returned. The supplied helpers expose a validated UUID
-request ID and status without copying response/error bodies into exceptions.
-Their defaults are three attempts with 100/200 ms backoff and an eight-second
-network deadline per attempt, shared by DNS, all address connections, TLS and
-HTTP. Configure one to ten attempts. Python cannot cancel an operating-system
-DNS lookup: at most eight daemon resolver workers may finish later. They never
-connect or receive events or keys; waiting for a resolver slot uses the same
-deadline. The helpers do not follow redirects or publish credentials to another
-endpoint.
-
-`GET /health` checks the API process. `GET /ready` checks API broker readiness;
-it says nothing about database persistence. Public metrics and administration
-routes return 404. Consumer health/metrics are internal. Use the SQL verification
-command in the deployment guide or the [operator guide](operations.md) to check
-stored IDs and consumer progress.
+| 202 with matching IDs | The queue accepted the events; check persistence separately when needed |
+| 400 | Fix the invalid event instead of retrying it unchanged |
+| 401 | Fix or rotate the key; keep unsent business events |
+| 404 or redirect | Correct the URL or endpoint settings |
+| 413 | Reduce event/request size or split the batch |
+| 429 | Retry the same content after a bounded delay |
+| 500/502/503 or another server failure | Keep the event; retry its original ID because delivery may be uncertain |
+| Timeout, connection loss or invalid response IDs | Keep the event and retry the same ID |
+| Untrusted TLS certificate | Fix the hostname or trusted CA; keep certificate verification enabled |
+
+Application errors have `error`, `message`, `request_id` and `timestamp` fields.
+The response also carries `X-Request-ID`. The example helpers expose a validated
+UUID request ID and status without putting response bodies in their exceptions.
+
+They default to three attempts with 100/200 ms delays and an eight-second network
+deadline per attempt. That deadline includes DNS, all address connections, TLS
+and HTTP. You can configure one to ten attempts. Python cannot cancel an OS DNS
+lookup, so at most eight daemon resolver workers may finish later. They never
+connect or receive events or keys. Waiting for a resolver slot uses the same
+deadline. Neither helper follows redirects or sends credentials to another URL.
+
+## Check health and storage separately
+
+`GET /health` checks the API process. `GET /ready` checks whether the API can
+accept events through the broker. It cannot confirm a PostgreSQL write. Consumer
+health and metrics stay on the private network; public metrics/admin routes
+return 404. Use the deployment guide's SQL query or the [operator guide](operations.md)
+to check stored IDs and worker progress.
diff --git a/docs/architecture.md b/docs/architecture.md
index 810da31..2bd8797 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -1,74 +1,89 @@
-# Architecture
+# How the collector works
-The deployment has five long-running services: Caddy, a Go API, Redpanda, a Go
-consumer and PostgreSQL. Initialization jobs create topics, apply migrations and
-set up the restricted writer login. Only Caddy publishes host ports 80/443.
+An application sends an event to the HTTP API. The API puts it in Redpanda,
+a Kafka-compatible event queue. A separate Go worker, called the consumer in
+the code, reads the queue and saves rows in PostgreSQL. The queue lets the API
+accept events while the database is temporarily unavailable. The API key
+provides the tenant label stored with each event.
-
+
-[Full diagram](assets/deployment.svg) · [Source and reproduction](figures/README.md)
+This view follows the event. The [deployment map](assets/deployment.svg) shows
+all five long-running services: Caddy, the Go API, Redpanda, the Go consumer and
+PostgreSQL. The [compact map](assets/deployment-mobile.svg) and
+[figure sources](figures/README.md) are also available. Startup jobs create the
+topics, apply migrations and configure the writer login. Only Caddy publishes
+host ports 80/443.
-The API maps a backend key to a tenant, validates the envelope, supplies receipt
-time and publishes to Redpanda. It returns 202 after all records covered by the
-response are acknowledged. It never contacts PostgreSQL. The producer uses
-bounded buffering, a five-second publish deadline, all-ISR acknowledgements and
-franz-go's idempotent producer.
+## The API waits for the queue
-The consumer reads at most 500 records, handles each partition in order and
-writes valid segments with one multi-row INSERT plus `ON CONFLICT DO NOTHING`.
-Each SQL statement commits atomically. Only then does the consumer commit those
-source offsets. A crash in between can replay the segment; the unique
-`(tenant_id,event_id)` key prevents another row. An HTTP batch can span partitions
-and SQL segments; it is not one transaction across the entire pipeline.
+The API checks the backend key, uses it to select a tenant, validates the event
+and adds receipt time. It returns 202 only after Redpanda acknowledges every
+record named in that response. It never contacts PostgreSQL.
-Malformed broker envelopes go to a separate quarantine topic on the same broker.
-The consumer waits for its acknowledgement before advancing the source offset.
-Database failures are retries, not quarantine. See [delivery semantics](delivery.md).
+Publication has bounded buffering and a five-second deadline. The franz-go
+producer uses idempotent production and waits for all in-sync replicas to
+acknowledge. The supplied deployment has one replica.
-## What the components own
+## The worker saves rows, then its read position
-| Component | Responsibility |
+The worker reads at most 500 records and handles each partition in order. It
+saves each valid segment using one multi-row INSERT with
+`ON CONFLICT DO NOTHING`. The statement commits all its rows together.
+
+After that succeeds, the worker saves its position in the queue, called an offset.
+A replacement worker resumes from the saved position. If the process stops after
+SQL commits but before the offset commits, it reads the events again. The unique
+`(tenant_id,event_id)` key keeps one row, preserving the first stored content.
+An HTTP batch can cross partitions and SQL segments; the entire request is not
+one database transaction.
+
+A malformed broker record goes to a separate quarantine topic for inspection.
+The worker waits for that write to be acknowledged before advancing past it.
+A database failure causes a retry. [Delivery details](delivery.md) cover both paths.
+
+## Find the code for each job
+
+| Code | Job |
| --- | --- |
-| `internal/api` and middleware | Authentication, per-tenant request limiting, validation, HTTP acknowledgements |
-| `internal/messaging` | Bounded publish, partition processing, acknowledged quarantine, offset ordering |
-| `internal/persistence` | Atomic batched SQL and first-content conflict handling |
-| `internal/service` | Supervision, drain, processing readiness and safe diagnostics |
-| `deploy/` | Canonical HTTPS Compose package, configuration generation, migrations/role initialization |
-| `internal/runenv` | Owned local test/demo/study orchestration; not a deployed service |
-| `examples/` | Importable callers and an application-owned SQLite outbox |
-| `internal/benchmark` | Explicit write comparisons, HTTPS load observation and recovery experiments |
-
-PostgreSQL, Redpanda and Caddy state use named volumes. The consumer has CONNECT,
-schema USAGE, SELECT and INSERT privileges; it is not a superuser and needs no
-TEMP or permanent-DDL privilege. Migrations use a separate admin login.
-The private Compose network is the deployment trust boundary; tenant API scoping
-does not provide PostgreSQL row-level isolation.
-
-## Why the writer changed
-
-The first [complete corrected study](../benchmarks/results/selfhost-copy-2026-11-04/README.md)
-compared single INSERT, batch INSERT and the actual temporary-table COPY/merge
-path. Batch INSERT had the lower median than COPY/merge in all 11 configurations.
-The default was changed separately, retaining atomic rollback, deduplication,
-restricted-role and deterministic crash-replay checks. The COPY transaction now
-lives as an explicit benchmark reference; changing the default does not relabel
-a different algorithm as COPY.
-
-A [new complete study](../benchmarks/results/selfhost-2026-11-04/README.md) records
-the resulting committed implementation. Repetition ranges overlap or reverse
-some individual timings. There is no universal/adaptive batch-size threshold or
-measured JSONB-versus-typed-table advantage.
-
-## Scope and tradeoffs
-
-The broker permits asynchronous acceptance and retained-log recovery during
-PostgreSQL outages, at the cost of another stateful service. For an application
-already satisfied by direct transactional PostgreSQL writes, that extra service
-may not be useful. The outbox pattern is reusable independently of this collector.
-
-This package targets one Compose host. One broker replica, finite log retention
-and a database backup do not provide high availability or automatic recovery from
-losing the only disks. There is no analytics dashboard, connector catalog, schema
-registry, generated SDK, automatic legacy import or business-payload validator.
-Applications own their business schemas and event IDs; operators own backups,
-disk growth and any database archival/deletion policy.
+| `internal/api` and middleware | Check keys, apply per-tenant request limits, validate events and return HTTP responses |
+| `internal/messaging` | Publish within buffer limits, read partitions, save bad records and advance offsets in order |
+| `internal/persistence` | Write atomic SQL batches and ignore an already stored event ID |
+| `internal/service` | Restart failed work, allow shutdown work to finish, report processing readiness and safe diagnostics |
+| `deploy/` | Run the HTTPS services, generate settings, apply migrations and set up database roles |
+| `internal/runenv` | Create and control isolated local test/demo/study projects; it is not a deployed service |
+| `examples/` | Reusable HTTP callers and an application-owned SQLite outbox |
+| `internal/benchmark` | Compare database writes, send HTTPS workloads and measure recovery |
+
+PostgreSQL, Redpanda and Caddy use named volumes. The consumer login has CONNECT,
+schema USAGE, SELECT and INSERT. It is not a superuser and needs neither TEMP nor
+permission to create permanent database objects. Migrations have a separate admin
+login. The private Compose network separates these services from public traffic.
+HTTP tenant checks do not add PostgreSQL row-level isolation.
+
+## Why the database writer uses INSERT
+
+The [first complete corrected study](../benchmarks/results/selfhost-copy-2026-11-04/README.md)
+compared one INSERT per row, one INSERT per batch and the original COPY path,
+which used a temporary table followed by a merge. Batch INSERT had a lower median
+elapsed time than COPY/merge in all 11 tested configurations.
+
+The writer changed to batch INSERT while retaining tests for rollback, duplicate
+IDs, restricted privileges and the exact crash/replay gap. COPY stays an explicit
+benchmark implementation. The [second complete study](../benchmarks/results/selfhost-2026-11-04/README.md)
+measures the changed writer. Some individual timings overlap or reverse the
+median ordering. No universal batch-size threshold or JSONB-versus-typed-table
+advantage was established, and the writer does not choose a method adaptively.
+
+## Decide whether the queue helps your application
+
+Redpanda holds events during PostgreSQL outages and retains records for replay.
+It also adds a stateful service to operate. If direct PostgreSQL transactions
+already solve the problem, that service may add little value. You can use the
+outbox pattern independently of this collector.
+
+The package runs on one Compose host with one broker replica and finite retention.
+A database backup does not recover queued events lost with the only broker disk.
+The package has no automatic high availability or recovery from host loss.
+Applications own event IDs and business validation. Operators own disk growth,
+backups and database archival/deletion. The saved events are available through SQL.
diff --git a/docs/article.md b/docs/article.md
index 39b4646..aa16336 100644
--- a/docs/article.md
+++ b/docs/article.md
@@ -1,76 +1,77 @@
-# Building an event collector around the failure boundaries
+# What happens after an event collector says "accepted"?
-An HTTP 202 can reach an application while PostgreSQL is unavailable. A failed
-HTTP request can also have put some records into a broker. Both are ordinary
-outcomes in an asynchronous collector. The useful question is what the caller
-should retain, what the consumer can replay, and how to check what survived.
+Suppose your checkout service has just saved a $25 order. It sends an
+order-completed event to IngestKit and receives HTTP 202. PostgreSQL is offline
+at the time. The event is waiting in Redpanda, the queue between the HTTP API
+and the database worker.
-IngestKit is a small Go collector built to make those boundaries inspectable:
-HTTPS → Go API → Redpanda → Go consumer → PostgreSQL. It now includes a
-self-contained Docker Compose deployment, copyable Python/Node callers and a
-working application outbox. The experiments changed the implementation too:
-batch INSERT beat the temporary-table COPY/merge strategy in every tested
-configuration by median, so the deployed writer became simpler.
+The response confirms queue acceptance; storage is a separate step. A lost
+response can cause the application to send the event again. A worker that stops
+after saving the row can also read it again. Keeping the same event ID makes
+both retries safe.
-This is a publication draft backed by [complete captures and methodology](../benchmarks/results/selfhost-2026-11-04/README.md)
-from clean revision [213e4cc](../benchmarks/results/selfhost-2026-11-04/manifest-1.json).
-It describes performed local experiments, not production adoption or a maximum
-throughput result. The complete earlier COPY-writer study is retained separately.
+IngestKit is a small Go collector you can deploy with Docker Compose. The repo
+also has Python and Node examples for sending events, and an order application
+that keeps pending events in its database.
-## Make it something another application can use
+## Follow the event to PostgreSQL
-The deployment contains the gateway, API, broker, consumer and database. Only
-Caddy publishes ports 80/443; database, Kafka, administration and metrics stay
-private. The consumer has a restricted writer login, while migrations use a
-separate admin login. Named volumes retain database, broker and certificate state.
+Your backend gives the event a UUID, a unique ID that stays the same when it
+retries. It also sends an event type, occurrence time and JSON-object payload.
+The API key selects a tenant, the label stored with each event. Callers cannot
+choose another tenant in the request body. The API adds the time it received the event.
-
+
-A host needs Docker/Compose, Git, OpenSSL and curl. Go builds inside Docker.
-With your own DNS hostname pointing to the server and ports 80/443 reachable:
+Caddy receives HTTPS traffic and forwards it to the Go API. The API checks the
+key and event, writes to Redpanda, and returns 202 after Redpanda acknowledges
+all events named in the response. It never connects to PostgreSQL. The worker
+reads the queue separately and writes rows in batches.
+
+Unknown request fields and JSON that PostgreSQL cannot store are rejected before
+entering the queue. Your application still validates its own business payload:
+the collector does not decide whether an order amount makes sense.
+
+The [deployment walkthrough](../deploy/README.md) starts with a fresh checkout,
+generates private settings, sends three events and finds their IDs in SQL.
+With your own hostname pointing at the server and ports 80/443 reachable, the
+startup commands are:
~~~sh
deploy/configure.sh events.example.com
docker compose --env-file deploy/.env -f deploy/compose.yml up -d --build --wait
~~~
-The configuration script creates fresh secrets in an ignored file with mode 0600 and
-refuses to overwrite an existing configuration. The [deployment walkthrough](../deploy/README.md)
-starts at cloning the repository, sends fixed checkout UUIDs and verifies those
-same IDs in SQL. Ordinary shutdown preserves volumes. Local tests verify HTTPS
-against an explicit private CA; they do not claim to have exercised public DNS
-or ACME certificate issuance.
-
-The HTTP contract is deliberately small: UUID, event type, occurrence timestamp
-and JSON-object payload. A backend key determines the tenant; the caller cannot
-supply a different tenant in its envelope. The API supplies receipt time. Unknown
-fields and JSON values that PostgreSQL cannot represent are rejected before
-publication. Business-payload validation remains in the application.
+Docker builds Go inside the images. The host needs Docker/Compose, Git, OpenSSL
+and curl. Only Caddy publishes ports; the API, queue, worker, database and metrics
+stay on the private network. Migrations use an admin login and the worker uses
+a restricted writer login. Named volumes keep the database, queue and certificates.
+The setup script creates secrets in an ignored mode-0600 file, refuses to replace
+an existing file, and ordinary shutdown preserves the volumes. Local tests use
+a trusted private certificate authority; public DNS and ACME issuance were not
+exercised by those tests.
-The [copyable clients](integration.md) have no package dependencies. They validate
-acknowledgement IDs, retry bounded transient/uncertain failures with the same
-serialized bytes, and return safe status/request-ID metadata. They keep keys on
-a trusted backend. They do not make an in-memory event survive a process crash.
+## First, save the event in the application
-## Start stable IDs in the application transaction
+A saved order does not by itself give you a saved event. If the application
+commits the order and then crashes before the HTTP send, the collector has
+nothing to recover. An in-memory retry loop disappears with the process.
-A successful order write followed by an HTTP send has a gap: the process can die
-between them. Retrying a request helps only if the application retained the event.
The [transactional outbox pattern](https://docs.aws.amazon.com/prescriptive-guidance/latest/cloud-design-patterns/transactional-outbox.html)
-addresses that creation gap by recording business state and pending delivery in
-one database transaction, with idempotent handling of repeated dispatch.
+puts the order and its pending event in one database transaction. They either
+commit together or neither does. A separate dispatcher reads the pending events
+and sends them to the collector.
-The included [SQLite application](../examples/outbox/README.md) makes that concrete.
-An order and its serialized event/UUID commit together. Creating the same order
-with the same amount returns the original event ID; conflicting business input
-fails. A separate one-shot dispatcher reads pending work, releases the SQLite
-connection, sends HTTP, and marks matching acknowledgements in another transaction.
-It holds no business write lock while waiting on the network.
-
-After loading the backend key as shown in the deployment guide:
+The [SQLite order example](../examples/outbox/README.md) stores the UUID and exact
+serialized event with the order. Creating the same order again with the same
+amount returns the original event ID; a different amount is rejected. Run these commands from the configured checkout
+with its initial generated key mapping. Use your hostname in API_URL.
+On another backend host, supply the URL
+and key through private application settings:
~~~sh
export API_URL=https://events.example.com
+INGESTKIT_API_KEY=$(sed -n 's/^API_KEYS={"\([0-9a-f]*\)":"default"}/\1/p' deploy/.env)
export INGESTKIT_API_KEY
python3 -m examples.outbox create-order --database private/orders.db \
--order-id order-123 --amount-cents 2500
@@ -78,191 +79,205 @@ python3 -m examples.outbox dispatch --database private/orders.db
python3 -m examples.outbox status --database private/orders.db
~~~
-The states are precise. `pending` still needs broker acknowledgement;
-`acknowledged` means matching HTTP 202 IDs, with PostgreSQL potentially catching
-up; `rejected` keeps a permanent 400/413 visible for repair. Authentication or
-network failures do not silently discard business events.
-
-There is another crash gap after the broker ACK but before the dispatcher marks
-its local row. A deterministic integration test pauses a test-only wrapper after
-an actual HTTP ACK, kills that child and dispatches again. The new process uses
-the saved UUID/body, and PostgreSQL still has one row. This example supports one
-dispatcher; multiple dispatchers need a claim/lease protocol in the application's
-own database. SQLite is the runnable example, not a requirement to add a second
-database to an application that already has transactions.
-
-## Put SQL before source progress
-
-The API waits for every broker acknowledgement covered by its response. The
-publish deadline is five seconds and buffering is bounded. HTTP batches are
-validated together, but are not broker transactions: an error can follow partial
-publication. A retry therefore reuses IDs rather than inventing replacements.
-
-The consumer's normal valid-record path is short:
-
-1. Read a bounded segment from a source partition.
-2. Execute one multi-row INSERT with `ON CONFLICT DO NOTHING`; commit PostgreSQL.
-3. Commit the handled source offsets.
-
-The unique key is `(tenant_id,event_id)`. A crash after step 2 and before step 3
-leaves stored rows with pending offsets. A replacement consumer replays them;
-conflicts preserve the first stored content. Reusing a UUID for different content
-is a caller error, not an update operation.
-
-
-
-[Open the full sequence](assets/delivery.svg). HTTP response timing and consumer
-processing can overlap after broker acceptance. The diagram's alternative segment
-does not imply that already committed offsets replay.
-
-This is an idempotent storage effect, not a transaction spanning Kafka and
-PostgreSQL. [Kafka's delivery-semantics discussion](https://kafka.apache.org/41/design/design/)
-is useful context: Kafka-to-Kafka transactions do not automatically make an
-external database write atomic with an offset update.
-
-Malformed broker envelopes take a separate acknowledged quarantine path. Source
-progress cannot skip a record whose quarantine write failed. A database outage
-is retried, not treated as malformed data. The [delivery contract](delivery.md)
-spells out these conditions and the finite retention/disk assumptions.
-
-## Test the crash window deliberately
-
-Randomly restarting a consumer is useful, but does not prove it died in the
-SQL-commit/offset-commit gap. The deterministic regression wraps the real store,
-pauses just after database commit, kills only that helper process, checks that
-the source offset is still pending and starts a replacement in the same group.
-Replay encounters the duplicate and advances progress; SQL still contains one row.
-
-Other real-service checks deny INSERT while database Ping still succeeds,
-restore the grant and verify processing readiness; rotate overlapping API keys;
-and restore a custom-format backup into a separate empty owned deployment while
-preserving the source. Safe consumer diagnostics report operation, error class,
-SQLSTATE and source coordinates, with repeated errors throttled. They exclude
-raw errors, credentials and payloads. Connectivity is not sufficient evidence of
-successful processing.
-
-## Measure the write path you actually deploy
+The dispatcher releases its SQLite connection before sending HTTP, so it holds
+no business write lock during the network wait. It marks the event `acknowledged`
+only after checking that the returned IDs match. A network or authentication
+failure leaves it `pending`. A permanent 400/413 rejection stays `rejected` and visible for repair.
+Acknowledged here means the queue accepted the event; PostgreSQL may still be
+catching up.
+
+The dispatcher can also crash after receiving 202 but before updating its local
+row. On restart, that row still says pending. Sending its saved UUID and body
+again is safe because the collector stores one row per tenant and event ID.
+A test pauses a separate dispatcher process just after an actual response, kills
+it and runs dispatch again. The database still contains one row.
+
+The example runs one dispatcher at a time. Multiple dispatchers need a claim or
+lease in the application's database. SQLite makes the pattern runnable here;
+an application with an existing transactional database can put its outbox there.
+The [Python and Node clients](integration.md) can also be used directly when the
+application already retains the events it needs to retry. They have no package
+dependencies, check the response IDs, retry the same serialized bytes and return
+safe status/request-ID metadata. Keys belong on the backend.
+
+## Then, save the row before saving the worker's place
+
+The worker needs to remember how far it has read through each queue partition.
+That saved position is called an offset. It determines where a replacement
+worker starts after a crash.
+
+For valid events, the worker does these operations in order:
+
+1. Read a bounded group of records from a partition.
+2. Save them with one multi-row INSERT and `ON CONFLICT DO NOTHING`.
+3. Save the read position in Redpanda after the database commit succeeds.
+
+The table's unique key is `(tenant_id,event_id)`. A crash between steps 2 and 3
+leaves the row saved and the read position behind. The next worker reads that
+event again. PostgreSQL sees the existing key, leaves the original row alone,
+and the worker can then save its new position.
+
+
+
+The crash test stops a helper exactly after the real SQL commit, checks that the
+queue position is still uncommitted, then starts a replacement in the same group.
+It verifies both the replay and the single stored row. Random restarts alone
+would not prove that this particular gap had been tested.
+
+The HTTP response and worker processing can run at the same time after queue
+acceptance; they have no single global packet order. The
+[complete request sequence](assets/delivery.svg) and [compact guide](assets/delivery-mobile.svg)
+show the separate acknowledgements. [Kafka's delivery discussion](https://kafka.apache.org/41/design/design/)
+explains the wider issue: a Kafka transaction does not automatically include an
+external PostgreSQL write. IngestKit reads events again and uses a unique database
+key to handle that gap. It keeps the first stored content; reusing an ID for
+different content is a caller error, not an update.
+
+If a queue record is malformed, the worker saves its original bytes and source
+details in a separate quarantine topic for inspection. It waits for that write
+to succeed before moving past the bad record. A database outage is retried; it
+does not turn valid events into quarantine records. The [delivery reference](delivery.md)
+covers the input restrictions, request limits and recovery assumptions.
+
+The API waits up to five seconds for publication and keeps buffering bounded.
+A failed HTTP batch can still have put some records into the queue; validation
+together does not make the batch one transaction across partitions or SQL writes.
+Keep the original IDs and content after an uncertain response.
+
+## The database comparison removed some code
+
+The original writer used COPY, PostgreSQL's bulk-loading mechanism. Its complete
+path created a temporary table, copied the events into it, merged them into the
+indexed event table with duplicate handling, and committed. That is more work
+than a plain COPY into an empty table.
[PostgreSQL's bulk-loading guidance](https://www.postgresql.org/docs/18/populate.html)
-explains why per-row commits are expensive and why COPY is useful for large
-loads. This collector's original strategy did more work than plain COPY into
-an empty table: create a temporary table, COPY into it, merge into an indexed
-target with conflict handling, then commit. The comparison measures complete
-strategies; it does not isolate the cost of each extra operation.
+explains the cost of committing each row and the use of COPY for large loads.
+The [recorded study](../benchmarks/results/selfhost-2026-11-04/README.md) used clean
+source [213e4cc](../benchmarks/results/selfhost-2026-11-04/manifest-1.json) and measured
+25 configurations three times each. The database comparison covered these complete implementations: one INSERT per
+row, one INSERT per batch, and COPY followed by a merge.
-The corrected study compares single INSERT, batch INSERT and that explicit
-COPY/staging/merge reference. Each method gets 5,000 submissions, the same schema,
-indexes, conflict policy and enabled database durability. Generation, reset,
-warm-up and exact verification are outside elapsed time; order rotates across
-three repetitions. Single INSERT commits every row, the others every batch.
+Each method submitted 5,000 events against the same table, indexes and duplicate
+policy, with database durability enabled. Input generation, reset, warm-up and
+verification happened outside the measured write time. Method order rotated
+across three runs. The single-row method committed every row; the other two
+committed every batch.
-For 256-byte payloads, no duplicates and batch 100, the final study recorded
-these median and min–max seconds across all three repetitions:
+For 256-byte payloads, batch size 100 and no duplicate IDs, the times were:
| Method | Median (s) | Range (s) |
| --- | ---: | ---: |
-| Single INSERT | 6.510 | 4.710–8.375 |
-| Batch INSERT | 0.155 | 0.121–0.247 |
-| COPY/staging/merge | 0.486 | 0.212–0.523 |
-
-The broader sweep covers batch sizes 1–1000, payloads up to 16 KiB and 10/50/90%
-duplicate submissions. Batch INSERT had the lower median than COPY/merge in all 11
-configurations in both studies. Some individual repetitions overlap or reverse
-that ordering. Duplicate cases insert fewer unique rows, so their submitted/s
-is not a clean percentage estimate of deduplication overhead.
-
-
-
-That evidence changed the default to one atomic batched INSERT. Existing rollback,
-deduplication and deterministic replay tests still pass; the deployed role no
-longer needs temporary-table privilege. COPY remains a distinct reference in the
-benchmark, rather than a label that silently follows the current default. A new
-complete study was run from the resulting committed code.
-
-This result does not identify a universal COPY crossover. It does not compare
-UNNEST or typed tables. [Tiger Data's batch-ingest exploration](https://www.tigerdata.com/blog/benchmarking-postgresql-batch-ingest)
-compares different bulk-loading methods and sizes; its numbers should not be
-transferred to this indexed, conflict-handling JSONB workload.
-
-## An offered rate is not a capacity result
-
-The HTTPS suite has 11 load configurations with three measured windows each.
-The baseline offers 1,000 events/s for ten seconds, in batches of 100 with 32
-clients and 256-byte payloads. Warm-up is two seconds; target SQL polling is 50 ms.
-Larger payloads use batch 10 to stay below the existing request cap.
-
-All three baseline windows attempted, acknowledged and independently verified
-10,000 events each, without reported limits. HTTP ACK p95 was 40.19–42.92 ms;
-receipt-to-observed-storage p95 was 101.61–103.08 ms. Those are different populations:
-one sample per successful request versus one per observed event.
-
-The rest of the report is less tidy, and should stay that way. Smaller batches
-show generator misses or boundary tails. At 10,000 offered/s, repetition 2 retained
-1,000 ambiguous IDs absent at its final deadline; the 16 KiB case's second repetition
-retained 160. They remain unknown, not proved never delivered, and are not counted
-as acknowledged success. A caller should retain and retry their original IDs.
-
-
-
-A late acknowledgement at the edge of a finite window does not itself prove
-saturation. Neither do missed generator schedules identify the collector's
-capacity. In-window ACK rate excludes late ACKs. Stored rate includes the whole
-window, request tail, observation drain and final verification. Selecting the
-best repetition or dividing later rows by an earlier denominator would tell a
-different, misleading story.
-
-The SQL metric is an upper bound: API receipt through the first completed query
-that sees a committed row, including polling/query overhead. `persisted_at` alone
-is not a commit clock. The observer uses a connection-owned pending-ID relation,
-so a transaction committing late cannot fall behind a timestamp cursor. Final
-ID/content verification is independent; rows discovered only then receive no
-invented latency sample. Receipt and SQL observation share the deployment clock,
-while the host schedules load with monotonic timing.
-
-## Recover, then reconcile
-
-The three availability experiments each run three repetitions:
-
-- PostgreSQL stop requested at 3s and start at 8s during a 15-second workload.
-- Consumer KILL requested at 3s and restart at 5s during the same offered 500/s load.
-- Broker stopped for eight seconds after stop completion, while 100 durable outbox
- events survive a failed attempt lasting more than the five-second publish deadline.
-
-Every acknowledged ID/content reconciled after the database and consumer cases.
-In the outbox case, a new dispatcher replayed the saved events to 100 accepted and
-stored unique IDs per repetition. Container start completion is not the same as
-catching up source progress. Actual control timestamps and all repetitions are
-retained; SQL-observer outages appear as gaps.
-
-
-
-These are availability experiments, not throughput headlines or exhaustive
-failure proofs. They complement the exact crash-window regression. The
-[operator guide](operations.md) covers readiness, lag, disk growth, key rotation
-and backup/restore. Restoring an older database does not rewind committed broker
-offsets: replay must be deliberate and can recover only data still retained.
-
-## Keep the limits with the result
-
-The environment was an M1 Max physical host with an OrbStack Linux Docker VM,
-with generator and SQL observer sharing that machine alongside existing workloads.
-The broker had one core and 1 GiB; the VM exposed 10 CPUs and about 16 GiB. Coarse Docker
-snapshots do not establish a sole bottleneck or a cloud-cost estimate.
-
-The new manifests inspect the actual broker process's fsync-bypass flag, topic
-write caching, database durability, image IDs/digests and trusted HTTPS protocol.
-An earlier development-mode capture had process-level fsync bypass enabled even
-though topic write caching was false. It remains [historical with an erratum](../benchmarks/results/local-2026-11-03/README.md);
-these corrected studies do not reuse it as deployment-performance evidence.
-
-The project has one broker replica and finite log retention on one host. It does
-not protect against losing that host or its disks. Applications own business
-schemas and IDs; operators own disk monitoring, backups and any SQL retention
-policy. Direct PostgreSQL writes may be a better choice when a broker adds no
-useful buffering or recovery boundary.
-
-Related reading includes [PostHog's capture/processing separation](https://posthog.com/docs/how-posthog-works/ingestion-pipeline)
-and [Segment's client-ID deduplication discussion](https://www.twilio.com/en-us/blog/insights/exactly-once-delivery).
-Their systems have different storage, scale and guarantees. Here, the reusable
-parts are the deployable HTTP boundary, durable application outbox, explicit
-commit ordering and experiments that keep their unknowns visible.
+| Single INSERT | 6.510 | 4.710 to 8.375 |
+| Batch INSERT | 0.155 | 0.121 to 0.247 |
+| COPY/staging/merge | 0.486 | 0.212 to 0.523 |
+
+The median is the middle of the three runs; the range shows all of them.
+Batch INSERT also had a lower median than COPY/merge in all 11 database
+configurations in both complete studies. The sweep covered batches from 1 to
+1,000, payloads up to 16 KiB, and 10%, 50% and 90% repeated submissions. Some
+individual runs overlapped or reversed the ordering. Repeated-ID cases created
+fewer new rows, so their submitted-events rate measures different work.
+
+The deployed worker now uses an atomic batched INSERT. Its rollback, duplicate,
+restricted-role and exact crash-replay tests still pass, and it no longer needs
+permission to create temporary tables. The original COPY transaction remains
+an independent benchmark method. A second complete study measured the changed
+writer from committed code.
+
+These runs establish a choice for this workload. They do not locate a universal
+batch size where COPY wins, compare UNNEST, or compare JSONB with typed tables.
+[Tiger Data's batch-ingest comparison](https://www.tigerdata.com/blog/benchmarking-postgresql-batch-ingest)
+uses other methods and sizes; its numbers cannot be transferred to this workload.
+The [full database plots](assets/database-batching.svg), including their
+[phone layout](assets/database-batching-mobile.svg), retain every measured run.
+
+## Count what was sent, accepted and found
+
+The HTTPS baseline tried to send 1,000 events per second for ten seconds: batches
+of 100, 32 clients and 256-byte payloads. After two seconds of warm-up, all three
+runs sent, received acknowledgements for, and found the stored content of 10,000
+events each, without reported limits.
+
+The response and storage measurements answer different questions. Across those
+runs, HTTP response p95 was 40.19 to 42.92 ms: 95% of successful requests completed
+within each run's p95. Receipt-to-observed-storage p95 was 101.61 to 103.08 ms,
+with one sample per observed event. SQL checks ran at a target interval of 50 ms,
+so that second measure includes waiting for the next query and the query itself.
+It is an upper bound on when storage became visible.
+
+The suite has 11 HTTP configurations, each run three times. Larger payloads use
+batches of 10 to fit the request limit. Some configurations missed the sending
+schedule or finished requests after the ten-second window. At 10,000 offered
+events/s, run 2 left 1,000 IDs with uncertain HTTP outcomes absent at the final
+check. The 16 KiB case left 160 in its second run. Those IDs remain unknown:
+the report neither counts them as acknowledged success nor proves they could
+never arrive later. An application should keep them for retry.
+
+A missed sending schedule is work the client did not submit. An acknowledgement
+just beyond a window boundary can happen without proving the server is saturated.
+The [full HTTP plots](assets/pipeline-load.svg) and [phone layout](assets/pipeline-load-mobile.svg)
+keep those cases and their limits. These short local runs do not establish
+maximum capacity.
+
+Rates also need a clear end time. The in-window acknowledgement rate counts only
+responses received inside the target window. The verified storage rate includes
+the window, unfinished requests, observation time and final verification.
+Counting late rows against only the earlier window would inflate that rate.
+
+To measure storage, the observer tracks the IDs it has not yet seen in a temporary
+table on its own database connection. A transaction that commits late therefore
+still gets checked. Scanning only an insertion timestamp such as `persisted_at`
+could miss it, because insertion and commit happen at different times. A final,
+independent query checks IDs and content. Rows found only then get no invented
+latency sample. API receipt and SQL observation use the deployment clock; the
+host schedules requests with a monotonic clock, which does not jump with wall time.
+
+## Stop the dependencies and check the rows
+
+The three recovery experiments each ran three times:
+
+| What stops | When | What was checked afterward |
+| --- | --- | --- |
+| PostgreSQL | Stop requested at 3s, start at 8s, during 15s of offered 500 events/s | Every acknowledged ID and its content reached storage |
+| Worker | KILL at 3s, restart requested at 5s, with the same offered load | Every acknowledged ID and its content reached storage after the group recovered |
+| Redpanda queue | Stopped for eight seconds after stop completion; 100 outbox events; a failed attempt longer than the five-second publish deadline | A new dispatcher resent saved events; each run finished with 100 accepted and stored unique IDs |
+
+The [recovery plots](assets/recovery.svg) and [phone layout](assets/recovery-mobile.svg)
+show all runs and actual control times. Gaps stay visible when SQL cannot be
+observed. A start command completing does not mean the worker has caught up,
+and these tests do not replace the exact crash-window test.
+
+Other real-service tests revoke INSERT while the database still answers Ping,
+then restore it and check processing readiness; rotate overlapping API keys; and
+restore a backup into a separate empty deployment while keeping the source intact.
+Worker logs report the failed operation, safe error class, SQLSTATE and queue
+position. Repeated failures are throttled; raw errors, keys, database URLs and
+payloads stay out of those messages. The [operator guide](operations.md) explains
+how to check progress, rotate keys and restore data. After an older database
+restore, replay must be planned explicitly: the queue's saved positions do not
+rewind with the database, and only retained records can fill the gap.
+
+## Where the results apply
+
+The tests ran on an M1 Max host with an OrbStack Linux Docker VM. The VM exposed
+10 CPUs and about 16 GiB RAM; Redpanda had one core and 1 GiB. The sender and SQL
+observer shared the machine with existing workloads. Coarse container snapshots
+cannot establish the sole bottleneck or a cloud-cost estimate.
+
+The manifests record image IDs/digests, the actual Redpanda fsync-bypass flag, topic
+write caching, database durability and verified HTTPS. An earlier development
+capture had process-level fsync bypass enabled even with topic write caching off.
+Its [historical correction](../benchmarks/results/local-2026-11-03/README.md) remains
+with the original samples. The corrected studies use new measurements.
+
+The supported deployment is one host, one queue replica and finite retention.
+Losing that host or its disks can lose events. Your application owns its business
+schema and event IDs; you own backups, disk monitoring and SQL retention. If direct
+PostgreSQL writes already meet your needs, a queue adds another service to operate.
+
+For related designs, read [PostHog's capture and processing description](https://posthog.com/docs/how-posthog-works/ingestion-pipeline)
+and [Segment's discussion of event-ID deduplication](https://www.twilio.com/en-us/blog/insights/exactly-once-delivery).
+Their storage, scale and guarantees differ. The [deployment map](assets/deployment.svg)
+and [compact map](assets/deployment-mobile.svg) show the services you would run
+for this implementation.
diff --git a/docs/assets/event-journey-mobile.svg b/docs/assets/event-journey-mobile.svg
new file mode 100644
index 0000000..1ee9ec9
--- /dev/null
+++ b/docs/assets/event-journey-mobile.svg
@@ -0,0 +1,46 @@
+
diff --git a/docs/assets/event-journey.svg b/docs/assets/event-journey.svg
new file mode 100644
index 0000000..878f954
--- /dev/null
+++ b/docs/assets/event-journey.svg
@@ -0,0 +1,653 @@
+
+
diff --git a/docs/assets/worker-replay-mobile.svg b/docs/assets/worker-replay-mobile.svg
new file mode 100644
index 0000000..282117e
--- /dev/null
+++ b/docs/assets/worker-replay-mobile.svg
@@ -0,0 +1,31 @@
+
diff --git a/docs/assets/worker-replay.svg b/docs/assets/worker-replay.svg
new file mode 100644
index 0000000..df29816
--- /dev/null
+++ b/docs/assets/worker-replay.svg
@@ -0,0 +1,688 @@
+
+
diff --git a/docs/delivery.md b/docs/delivery.md
index 6e0ce94..950bd11 100644
--- a/docs/delivery.md
+++ b/docs/delivery.md
@@ -1,103 +1,120 @@
-# Delivery semantics
+# What "accepted" and "saved" mean
-The [HTTP reference](api.md) defines the request envelope, limits and responses.
-The promise is broker acknowledgement followed by asynchronous, replay-safe
-PostgreSQL storage. The application must retain stable IDs and content when
-delivery is uncertain.
+The application, queue and database finish their work at different times. HTTP
+202 confirms that Redpanda accepted the event. A background worker saves it in
+PostgreSQL afterward. Keep the original event ID and content whenever you are
+unsure whether a request arrived. The [HTTP reference](api.md) lists the request
+fields, limits and responses. The API key selects the tenant label; event IDs
+are unique within that tenant.
-
+## What happens if the worker stops after writing?
-[Full sequence](assets/delivery.svg) · [Figure sources](figures/README.md)
+The worker saves the event first, then saves its position in the queue. That
+position is called an offset. It tells the next worker where to resume.
-The lower sequence segment is an alternative crash path. HTTP response timing
-and consumer processing are concurrent after broker acceptance; the figure is
-not a global ordering of every network packet.
+
-## Three boundaries
+If the process stops between those operations, the next worker reads the same
+event again. PostgreSQL's unique `(tenant_id,event_id)` key ignores the repeated
+insert. The first stored content stays unchanged. Sending different content
+with the same ID is a caller error; the database does not compare or update it.
-| Boundary | What it establishes | What remains pending |
+The [full HTTP sequence](assets/delivery.svg), [compact sequence](assets/delivery-mobile.svg)
+and [figure sources](figures/README.md) give the wider request path. HTTP response
+timing and worker processing can overlap after queue acceptance. The lower segment
+in the full sequence is an alternative crash path, not a global packet order.
+
+## What each completed operation tells you
+
+| Completed operation | What is known | What may still need to happen |
| --- | --- | --- |
-| HTTP 202 with matching IDs | The broker acknowledged all response records | Consumer processing and PostgreSQL storage |
-| SQL statement commits | A valid consumer segment stored atomically; conflicting IDs kept their first stored content | Source-offset commit |
-| Source offsets commit | Successfully handled source records can be skipped by this consumer group | Later application processing and operator retention/backup policy |
-
-The publisher waits at most five seconds and uses bounded buffers. A timeout,
-503 or interrupted response can be ambiguous: some records may already exist in
-the log. A validated HTTP batch is not a broker transaction and can span several
-partitions/SQL segments. Retry the same UUIDs and content. The supplied clients
-check the complete acknowledgement rather than assuming any 202 is success.
-
-PostgreSQL has a unique `(tenant_id,event_id)` key. Replaying a segment after SQL
-commit and before offset commit cannot create another row. Reusing an ID with
-different content is a caller error: conflicts are ignored, not compared or
-updated. Tenant scoping at HTTP is not database row-level isolation. There is no
-transaction spanning Kafka and PostgreSQL or unconditional exactly-once claim.
-
-A separate [application outbox](../examples/outbox/README.md) saves business state
-and an event in one local transaction. Its acknowledged state means broker ACK,
-not PostgreSQL persistence. A crash after HTTP ACK but before marking the outbox
-row leaves that event pending; a new dispatcher resends its original bytes/UUID.
-
-## Failure behavior
-
-| Failure | Behavior |
+| HTTP 202 with matching IDs | The queue acknowledged every record named in the response | The worker saves the events to PostgreSQL |
+| SQL statement commits | The valid segment is saved atomically; repeated IDs keep their first content | The worker saves its queue position |
+| Source offsets commit | This consumer group can resume past the handled records | Later application processing, retention and backups |
+
+The publisher waits at most five seconds and keeps buffering bounded. A timeout,
+503 or interrupted response may occur after some records reached the queue.
+The API validates an HTTP batch together, but publication is not a broker
+transaction and the batch can span partitions and SQL segments. Resend the same
+UUIDs and content. The example clients check all returned IDs before calling a
+request successful.
+
+The unique key makes repeated storage safe. It does not create one transaction
+across Kafka and PostgreSQL, or an unconditional exactly-once guarantee. HTTP
+checks the tenant selected by the key; PostgreSQL row-level isolation is separate.
+
+An [application outbox](../examples/outbox/README.md) covers an earlier gap: it
+saves the business change and pending event in one local transaction. If its
+dispatcher stops after receiving 202 but before marking the local row, the event
+stays pending. The next process resends the original UUID and bytes. An
+acknowledged outbox row confirms queue acceptance, not the PostgreSQL write.
+
+## How failures are handled
+
+| Failure | What the collector does |
| --- | --- |
-| PostgreSQL unavailable or writes denied | Retry; keep affected source progress uncommitted |
-| SQL commit followed by consumer crash | Replay the same IDs; ignore storage duplicates |
-| Malformed broker envelope | Preserve original bytes/key/headers/source coordinates in the separate quarantine topic |
-| Quarantine unavailable | Do not advance past that record |
-| Rebalance or offset-commit failure | Rejoin from committed offsets; unfinished work may replay |
-| Broker unavailable | HTTP may fail uncertainly; application outbox retains pending events |
-| Shutdown deadline exceeded | Exit with failure; do not claim a successful drain |
-
-The consumer polls at most 500 records and processes each partition sequentially.
-Its processing/retry window is fifteen seconds; its group session timeout is ten
-seconds. Source progress follows successful storage or acknowledged quarantine.
-Fetch-byte settings guide requests; they are not a hard process-memory ceiling.
-Shutdown stops new polls and gives current work ten seconds; it does not drain
-the whole retained log.
-
-Consumer readiness includes failed storage, quarantine and offset operations.
-Connectivity alone cannot clear a processing failure. After fixing the cause,
-the matching operation must succeed (or a process restart starts fresh state).
-Use [safe diagnostics and progress checks](operations.md), not API readiness
-alone, to assess a stuck consumer.
-
-## Durability and observation
-
-The deployment uses one broker replica and seven-day event/quarantine retention.
-Topic `write.caching=false` and the actual broker process's
-`--unsafe-bypass-fsync=false` are both verified. PostgreSQL fsync and synchronous
-commit remain enabled. These are configuration checks, not a physical power-loss
-experiment or protection from losing the only host/disk. An outage beyond retained
-data can leave an unrecoverable gap. PostgreSQL rows have no automatic expiry.
-Restoring an older database does not rewind broker offsets; see the explicit
-[backup/restore and retained-log replay procedure](operations.md).
-
-`persisted_at` is an insertion timestamp, not an exact physical commit clock.
-The study records API receipt to the first completed SQL observation of a
-committed row, including polling/query overhead. Receipt and SQL observation use
-the deployment clock; host monotonic timing schedules requests. Final ID/content
-verification is independent. An observer gap cannot provide exact commit times.
-
-## Representable payloads
-
-The API validates structure and PostgreSQL JSONB representation, not business
-schema. Payloads must be objects, valid UTF-8 with paired Unicode surrogate
-escapes, no NUL in strings/keys, and numeric representations within 131,072 integer
-digits and 16,383 fractional digits. The root counts as level one of a conservative
-64-level nesting bound. Envelope text and tenant IDs also reject NUL and invalid
-Unicode. These checks run before HTTP publication and on broker decoding; an
-incompatible broker record is quarantined rather than retried as a valid event.
-See [PostgreSQL JSON restrictions](https://www.postgresql.org/docs/18/datatype-json.html).
-
-For private inspection, define the deployment `dc` helper from the operator guide:
+| PostgreSQL is unavailable or denies writes | Retries and keeps the affected queue position uncommitted |
+| Worker crashes after SQL commit | Reads the same IDs again; PostgreSQL ignores the duplicate inserts |
+| Broker record has an invalid envelope | Saves its original bytes/key/headers and source coordinates in the quarantine topic |
+| Quarantine write fails | Keeps the source position before that record |
+| Consumer group rebalances or an offset commit fails | Resumes from committed offsets; unfinished work may be read again |
+| Broker is unavailable | HTTP may fail with an uncertain outcome; the application outbox keeps its pending events |
+| Shutdown runs out of time | Exits with failure instead of reporting a completed drain |
+
+The worker polls at most 500 records and processes each partition sequentially.
+It has fifteen seconds for a processing/retry cycle and a ten-second group
+session timeout. It advances only after storage or acknowledged quarantine.
+Fetch-byte settings guide broker requests; they do not cap total process memory.
+Shutdown stops new polls and allows ten seconds for current work, not the whole
+retained queue.
+
+Consumer readiness tracks failed storage, quarantine and offset operations.
+A successful connectivity check cannot clear one of those failures. After the
+cause is fixed, the failed operation must succeed; restarting the process starts
+fresh health state. Check [diagnostics and actual progress](operations.md), since
+API readiness alone cannot tell you whether database storage is moving.
+
+## How long recovery remains possible
+
+The deployment has one broker replica. Event and quarantine records have seven-day
+retention. Both topic `write.caching=false` and the actual process flag
+`--unsafe-bypass-fsync=false` are verified. PostgreSQL fsync and synchronous
+commit stay enabled. These checks establish the configuration; they are not a
+physical power-loss experiment. Losing the only host or disk can lose data, and
+an outage longer than retained history can leave a gap that cannot be recovered.
+PostgreSQL rows have no automatic expiry.
+
+An older database restore does not rewind the queue's saved offsets. Plan replay
+from retained data using the [restore procedure](operations.md).
+
+The study's `persisted_at` is an insertion timestamp, not an exact commit clock.
+Storage timing starts when the API receives an event and ends when a completed
+SQL query first sees its committed row. It includes polling/query delay. Receipt
+and SQL observation use the deployment clock; the host uses monotonic time for
+request scheduling. A final independent query checks IDs and content. No exact
+commit time can be recovered from a gap in observation.
+
+## JSON the database can store
+
+The API checks event structure and PostgreSQL JSONB limits. Your application
+checks the business schema. A payload must be a JSON object with valid UTF-8,
+paired Unicode surrogate escapes and no NUL (zero character) in strings or keys. Numbers must
+fit within 131,072 integer digits and 16,383 fractional digits. The nesting limit
+is 64 levels, counting the root as one. Envelope text and tenant IDs also reject
+NUL and invalid Unicode.
+
+The same checks run before HTTP publication and when reading broker records.
+An incompatible broker record goes to quarantine instead of blocking the queue
+as a repeatedly failing valid event. See [PostgreSQL's JSON restrictions](https://www.postgresql.org/docs/18/datatype-json.html).
+
+For private inspection, first define the deployment `dc` helper from the operator
+guide, then run:
~~~sh
dc exec -T redpanda rpk topic consume ingestkit.dlq -n 1 -X brokers=redpanda:9092
~~~
-Quarantine contains data, including base64 original bytes. Inspect privately,
-repair the envelope and resubmit through the authenticated API with its original
-ID. If the original ID is invalid, choose a new one deliberately. Do not bulk
-replay unchecked quarantine or skip source offsets to hide an error.
+Quarantine includes event data and base64-encoded original bytes. Inspect it
+privately, repair the envelope and send it through the authenticated API with
+the original ID. Choose a new ID deliberately if the original is invalid.
+Do not replay unreviewed records in bulk or skip offsets to hide a failure.
diff --git a/docs/development.md b/docs/development.md
index 223803c..fa507fd 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -1,13 +1,16 @@
-# Development
+# Develop and test IngestKit
-For deployment, use [deploy/README.md](../deploy/README.md). The root Compose file
-is the local development stack with loopback dependency ports and public demo
-credentials. It is distinct from the private HTTPS server package.
+For a server, follow [deployment](../deploy/README.md). The root Compose file is
+for local development: it exposes dependency ports on loopback and uses public
+demo credentials. The separate deployment package provides private services
+behind HTTPS.
-The module requires Go 1.24+. Container builds and CI pin Go 1.26.10. Docker with
-Compose 2.24.4+, OpenSSL and Python 3.9+ are required by the complete local test
-harness; Node is required for its caller tests (CI selects Node 24). PostgreSQL 18.6,
-Redpanda 26.2.6 and Caddy 2.11.7 are the recorded deployment versions.
+## Start the local stack and run checks
+
+Use Go 1.24+, Docker with Compose 2.24.4+, OpenSSL and Python 3.9+. The complete
+harness also needs Node for the caller tests; CI selects Node 24. Container builds
+and CI pin Go 1.26.10. The recorded deployment runs PostgreSQL 18.6, Redpanda 26.2.6
+and Caddy 2.11.7.
~~~sh
make up
@@ -23,39 +26,45 @@ make test-integration
make down
~~~
-`make down` preserves normal development volumes. Integration tests create their
-own projects, ports and volumes and verify ownership before control/cleanup.
-They require the script's explicit setup flag and real services; missing setup
-fails rather than silently skipping. Evidence stays under ignored `tmp/runs/`.
-Never substitute a global Docker prune or reset another project's database.
+`make down` keeps the development volumes. Integration tests create their own
+projects, ports and volumes, check ownership, then control or remove only those
+resources. Use the integration script, which supplies the required setup flag;
+tests fail if that setup is missing. They do not silently skip real-service
+checks. Private evidence goes under ignored `tmp/runs/`. A global Docker prune
+or reset of another project's database is never part of test cleanup.
-The full integration gate covers trusted HTTPS and private ports, restricted SQL
-privileges, first-event/content checks, denied-write readiness and recovery,
-credential overlap/recreate, source-preserving backup restore, reusable callers,
-outbox outage/after-ACK crash, broker/SQL failures, quarantine, rebalance and drain.
-It also runs the small study, interruption/resume and all three real recovery
-experiments. The process budget is 20 minutes; full timing studies stay out of CI.
+The full integration suite checks trusted HTTPS and published ports, restricted
+writer privileges, stored IDs/content, readiness after denied writes, key overlap
+and recreation, backup restore into a separate target, reusable callers, outbox
+outage/after-ACK crash, broker/SQL failures, quarantine, rebalance and shutdown.
+It also runs the small study, interruption/resume and the three recovery scenarios.
+The Go process has a 20-minute budget; full timing studies stay out of CI.
-## Configuration and migrations
+## Configure a local process
The root Compose defaults work without an environment file. [.env.example](../.env.example)
-lists local overrides. Runtime processes outside Compose require explicit
-`API_KEYS` or `DATABASE_URL`, plus `BROKERS`. Other settings include `HTTP_ADDR`,
+lists overrides. Outside Compose, the API needs `API_KEYS`, the consumer needs
+`DATABASE_URL`, and both need `BROKERS`. Other settings are `HTTP_ADDR`,
`METRICS_ADDR`, `EVENT_TOPIC`, `DLQ_TOPIC`, `CONSUMER_GROUP` and `RATE_LIMIT_RPS`.
-Deployment configuration is a private data file, never shell-sourced by the harness.
+The deployment harness reads its private settings as data; it never sources that
+file as a shell script.
+
+Only `migrations/showcase` runs. Applied migrations are recorded separately in
+`public.ingestkit_schema_migrations` with `search_path=public`. Existing legacy
+tables and migration records stay untouched; there is no automatic legacy import.
+
+## Check processing, not just connectivity
-Only `migrations/showcase` is applied, using the separate
-`public.ingestkit_schema_migrations` ledger and `search_path=public`. Existing
-legacy tables/ledgers are preserved; they are not automatically imported.
+`/health` checks that a process is alive. API `/ready` checks broker acceptance.
+The consumer also remembers failed storage, quarantine and queue-progress
+operations. An unrelated success or a database Ping cannot clear those failures.
+Fix the cause and let the matching operation succeed. A new process starts with
+fresh health state, so inspect progress after a restart too.
-`/health` is liveness. API `/ready` probes broker acceptance. Consumer readiness
-also latches failed storage/quarantine/progress operations; a successful Ping or
-unrelated operation cannot clear them. Fix the cause and let the matching
-operation succeed. A process restart starts new health state, so check actual
-progress as well. Shutdown stops new polls and gives current work a ten-second
-drain budget; exceeding it exits with failure.
+Shutdown stops new polls and gives the current work ten seconds to finish. If
+that budget expires, the process exits with failure.
-## Walkthroughs and measurements
+## Run the walkthroughs and experiments
~~~sh
make demo DEMO_FLAGS=-cleanup
@@ -63,27 +72,27 @@ make demo-recovery DEMO_FLAGS=-cleanup
make bench-study-smoke STUDY_FLAGS='-out tmp/studies/my-smoke -seed 42'
~~~
-Demos without `-cleanup` stop their own services and retain volumes; each prints
-its exact cleanup command. They use development HTTP, while the registered
-study and deployment integration checks use the self-hosted HTTPS profile and
-explicit CA trust. See [examples](../examples/README.md) and the
+Without `-cleanup`, demos stop their own services and preserve volumes, then
+print the command to remove that run. Demos use development HTTP. The registered
+study and deployment checks use the HTTPS profile and explicitly trust its local
+certificate authority. See [examples](../examples/README.md) and the
[experiment guide](../benchmarks/README.md).
-Full measurements require clean committed source, run sequentially and destroy
-only their owned stacks after collecting evidence. Do not edit sources or run
-other test/figure loads while timing them. Registered-study resume rejects
-changed source, controls or runtime/image identity. [Figure generation](figures/README.md)
-is optional development tooling, separate from runtime dependencies.
+Before full measurements, commit all source and run studies sequentially. Each
+run collects evidence and destroys only its own stack. Editing source or running
+other tests/figure jobs during timing changes the comparison. Resume rejects
+changed sources, controls and runtime/image identity. [Figure tools](figures/README.md)
+are optional development dependencies; the collector does not need them.
-## Troubleshooting
+## Troubleshoot a local run
-- Port collision: change the matching development override or use an owned demo.
-- 401: inspect the key mapping; preserve unsent application events.
-- 503: inspect broker readiness and bounded publication pressure; retry stable IDs.
-- 202 but no SQL row: check consumer readiness, lag, quarantine and the same UUID.
-- Migration failure: inspect the actual ledger/error; do not force a version or delete volumes.
+- Port collision: change the matching development setting or use an isolated demo.
+- 401: check the key mapping and keep unsent application events.
+- 503: check broker readiness and publication pressure, then retry the same IDs.
+- 202 with no SQL row: check worker readiness, queued work and quarantine; look for the same UUID.
+- Migration failure: inspect the ledger/error before changing anything; do not force a version or delete volumes.
-For the deployed package, follow the [operator recipes](operations.md), including
-safe logs, key refresh and fresh-target restore. Both broker process fsync bypass
-and topic write caching matter; the [historical capture correction](../benchmarks/results/local-2026-11-03/README.md)
-is retained rather than rewriting old evidence.
+The [operator guide](operations.md) has the deployed procedures for logs, key
+rotation and fresh-target restore. Both the broker process's fsync bypass and
+topic write caching affect durability. The [historical correction](../benchmarks/results/local-2026-11-03/README.md)
+explains an earlier development-mode capture without changing its raw data.
diff --git a/docs/figures/README.md b/docs/figures/README.md
index ee7f573..0122cc2 100644
--- a/docs/figures/README.md
+++ b/docs/figures/README.md
@@ -1,16 +1,71 @@
-# Figure sources and reproduction
+# Diagrams and experiment plots
-The diagrams describe source revision [213e4cc](../../benchmarks/results/selfhost-2026-11-04/manifest-1.json).
-Their JSON sources cite the actual gateway, API, consumer, SQL and migration code.
-The charts read the [audited study index](../../benchmarks/results/selfhost-2026-11-04/index.json),
-including every repetition and reported limit. No chart uses the historical
-fsync-bypassed pipeline captures.
+Start with the two event-story diagrams. One follows a request to storage; the
+other shows the exact place a worker can stop and safely read the event again.
+The architecture and sequence sources point to runtime revision 799106a.
-## Generate the charts
+## Where does an event wait?
-The recorded plotting environment was Python3.12.14 and matplotlib3.11.2.
-These are development tools; deployed services and copied HTTP clients do not
-need matplotlib. From the repository root, in a Python3.12 environment:
+
+
+The API returns 202 after queue acknowledgement. PostgreSQL may still be pending.
+This is the logical event path: the endpoint groups Caddy and the Go API. The
+[full deployment map](../assets/deployment.svg) and
+[phone map](../assets/deployment-mobile.svg) show the separate services and their
+public/private ports.
+
+## Why does replay keep one row?
+
+
+
+The unique tenant/event ID key makes the repeat safe. The
+[full request sequence](../assets/delivery.svg) and
+[phone guide](../assets/delivery-mobile.svg) include HTTP acceptance as well.
+HTTP responses and worker processing can overlap after queue acceptance.
+
+## How does batching affect writes?
+
+
+
+Each panel changes one input. Dots show all three runs; marks show the median
+and min/max, not confidence intervals. Duplicate workloads submit more events
+than the number of new rows inserted. Read those two rates separately. The
+[results](../../benchmarks/results/selfhost-2026-11-04/README.md) explain why the
+measured comparison led to batch INSERT.
+
+## Did the HTTP client send its target load?
+
+
+
+Compare the target with attempted and acknowledged counts before reading latency.
+Hollow points retain cases with limits, including responses just outside the
+window. ACK timing samples requests; SQL timing samples events first seen in
+committed rows and includes polling/query delay. Neither establishes maximum capacity.
+
+## What happened during the outages?
+
+
+
+Blank sections are SQL observation gaps. Fault lines mark Docker control completion,
+not the exact moment a service became usable. Outbox points are saved snapshots,
+with no fabricated line between them. In the database and worker panels, pending counts queue-acknowledged events the
+SQL observer has not yet seen. That observation count is not an instantaneous
+database or Kafka backlog. In the outbox panel, pending counts application rows
+not yet marked acknowledged locally; their delivery outcome can be uncertain.
+Read [all outcomes and controls](../../benchmarks/results/selfhost-2026-11-04/README.md)
+with the plots.
+
+## Regenerate the measured plots
+
+[verification.json](verification.json) records the original export and chart
+checks. [story-verification.json](story-verification.json) covers the new diagrams
+and their phone guides. The charts use the [audited study index](../../benchmarks/results/selfhost-2026-11-04/index.json),
+including all runs and limits, from source
+[213e4cc](../../benchmarks/results/selfhost-2026-11-04/manifest-1.json).
+They do not use the earlier fsync-bypassed pipeline samples.
+
+The recorded chart tools were Python 3.12.14 and matplotlib 3.11.2. In a Python
+3.12 environment, run from the repository root:
~~~sh
python3 -m venv .venv
@@ -20,21 +75,40 @@ python3 -m venv .venv
python3 docs/figures/render_mobile_guides.py
~~~
-Optional `--preview-dir tmp/figure-previews` also writes PNGs for inspection.
-The generator independently audits the captures before plotting, fixes SVG IDs,
-omits timestamps, embeds portable font outlines and writes desktop/mobile layouts
-from the same measurements. Mobile layouts increase type size and stack legends;
-no repetitions or limits disappear. The compact deployment/delivery guides are
-source-cited typographic companions to the full Archify diagrams.
+The generator audits the capture first. It fixes SVG IDs, omits timestamps and
+embeds font outlines. `--preview-dir tmp/figure-previews` also writes PNGs.
+Phone plots use larger type and stacked legends with the same measurements.
+These are optional development tools; deployed services and copied clients do
+not need matplotlib.
-## Reproduce the full diagrams
+## Regenerate the event-story diagrams
+
+[event-journey.architecture.json](event-journey.architecture.json) and
+[worker-replay.sequence.json](worker-replay.sequence.json) include their source
+ranges. Set `ARCHIFY_CLI` to the installed Archify 3.2.0 `bin/archify.mjs` path:
+
+~~~sh
+node "$ARCHIFY_CLI" finalize architecture docs/figures/event-journey.architecture.json \
+ .archify/architecture-event-journey-20261104-123448/event-journey.html \
+ --repo-root "$PWD" --quality showcase --json
+node "$ARCHIFY_CLI" finalize sequence docs/figures/worker-replay.sequence.json \
+ .archify/sequence-worker-replay-20261104-123448/worker-replay.html \
+ --repo-root "$PWD" --quality showcase --json
+python3 docs/figures/render_story_guides.py
+~~~
+
+Open the HTML and choose Export, then SVG Auto. Save the diagram exports as
+`docs/assets/event-journey.svg` and `docs/assets/worker-replay.svg`. They adapt
+to light/dark themes and exclude viewer controls. The small phone SVGs are reading
+guides generated by [render_story_guides.py](render_story_guides.py); they explain
+the same behavior without shrinking a full trace onto a phone.
+
+## Reproduce the detailed technical views
[deployment.architecture.json](deployment.architecture.json) and
-[delivery.sequence.json](delivery.sequence.json) were generated with Archify3.2.0,
-then passed its showcase validation, strict artifact and real-browser gates.
-The HTML and browser receipts live in the ignored `.archify/` directory.
-With an installed Archify CLI, set `ARCHIFY_CLI` to its absolute
-`bin/archify.mjs` path and run from this repository:
+[delivery.sequence.json](delivery.sequence.json) describe the measured runtime
+at 213e4cc. They passed Archify showcase, strict-artifact and real-browser checks.
+Their HTML and receipts live under ignored `.archify/`:
~~~sh
node "$ARCHIFY_CLI" finalize architecture docs/figures/deployment.architecture.json \
@@ -45,48 +119,11 @@ node "$ARCHIFY_CLI" finalize sequence docs/figures/delivery.sequence.json \
--repo-root "$PWD" --quality showcase --json
~~~
-Open each resulting HTML and choose **Export → SVG · Auto**. Save the full clean
-exports as `docs/assets/deployment.svg` and `docs/assets/delivery.svg`. They include
-automatic light/dark styling and exclude viewer controls. The checked repository
-identity is the original SSH remote; source links are intentionally local-only.
-A fresh changed candidate needs a new browser-evidence directory as documented by
-Archify. The compact reading guides are generated separately by
-[render_mobile_guides.py](render_mobile_guides.py), not described as packet traces.
-
-[Verification record and asset hashes](verification.json) cover the checked exports,
-regeneration and visual review at800px and390px. Charts use an opaque light panel
-for contrast on either page background; the diagram exports adapt to host theme.
-
-## Inspect the results
-
-
-
-[Full deployment diagram](../assets/deployment.svg). Persistent volumes and the
-single-host failure domain matter as much as the arrows; see the
-[deployment guide](../../deploy/README.md).
-
-
-
-[Full sequence](../assets/delivery.svg). The second segment is an alternative
-crash path, not a claim that an already committed offset replays. HTTP response
-and consumer processing are concurrent after broker acceptance.
-
-
-
-Submitted/s differs from inserted unique/s for duplicate workloads. Dots retain
-all three repetitions; min–max/median marks are descriptive, not confidence intervals.
-
-
-
-Hollow markers retain limits, including ordinary finite-window tails. ACK samples
-are successful requests; SQL samples are first-observed committed events. The
-latter include polling/query delay. Neither panel establishes maximum capacity.
-
-
+Export SVG Auto as `docs/assets/deployment.svg` and `docs/assets/delivery.svg`.
+The repository identity uses SSH, so source navigation is local-only. A changed
+candidate needs fresh browser evidence as described by Archify. The original
+compact guides come from [render_mobile_guides.py](render_mobile_guides.py).
-SQL-observer gaps remain blank. Fault lines mark Docker control completion, not
-an exact service-availability transition. Outbox points are state snapshots;
-intermediate changes are not fabricated. Pending acknowledged counts are based
-on observation, not an instantaneous database backlog. Read the
-[methodology and all outcomes](../../benchmarks/results/selfhost-2026-11-04/README.md)
-with the figures.
+Figures were checked at 800px content width and a 390px phone viewport. Plot
+panels keep an opaque light background for contrast; diagram exports follow
+the host theme. Export hashes identify the files that were checked.
diff --git a/docs/figures/event-journey.architecture.json b/docs/figures/event-journey.architecture.json
new file mode 100644
index 0000000..c8693ad
--- /dev/null
+++ b/docs/figures/event-journey.architecture.json
@@ -0,0 +1,199 @@
+{
+ "schema_version": 1,
+ "diagram_type": "architecture",
+ "meta": {
+ "title": "From an order event to a database row",
+ "locale": "en",
+ "output": ".archify/architecture-event-journey-20261104-123448/event-journey.html",
+ "quality_profile": "showcase",
+ "repository": {
+ "url": "git@github.com:feat7/ingestkit.git",
+ "revision": "799106aeed58f6618bdc4b3711a84e11000fb0b5",
+ "link_mode": "local-only"
+ },
+ "legend": {
+ "mode": "hidden"
+ }
+ },
+ "components": [
+ {
+ "id": "application",
+ "type": "external",
+ "label": "1. Your application",
+ "sublabel": "Saves an event ID",
+ "pos": [
+ 40,
+ 40
+ ],
+ "size": [
+ 164,
+ 72
+ ],
+ "sources": [
+ {
+ "path": "examples/outbox/app.py",
+ "line": 38,
+ "end_line": 54
+ },
+ {
+ "path": "examples/checkout/ingest_client.py",
+ "line": 73,
+ "end_line": 95
+ },
+ {
+ "path": "examples/checkout/ingest_client.py",
+ "line": 142,
+ "end_line": 158
+ }
+ ]
+ },
+ {
+ "id": "endpoint",
+ "type": "backend",
+ "label": "2. HTTPS endpoint",
+ "sublabel": "Caddy + Go API",
+ "pos": [
+ 310,
+ 40
+ ],
+ "size": [
+ 164,
+ 72
+ ],
+ "sources": [
+ {
+ "path": "deploy/Caddyfile",
+ "line": 4,
+ "end_line": 11
+ },
+ {
+ "path": "internal/api/ingest.go",
+ "line": 31,
+ "end_line": 53
+ }
+ ]
+ },
+ {
+ "id": "queue",
+ "type": "messagebus",
+ "label": "3. Event queue",
+ "sublabel": "Redpanda holds the event",
+ "pos": [
+ 580,
+ 40
+ ],
+ "size": [
+ 164,
+ 72
+ ],
+ "sources": [
+ {
+ "path": "internal/messaging/publisher.go",
+ "line": 49,
+ "end_line": 94
+ }
+ ]
+ },
+ {
+ "id": "worker",
+ "type": "backend",
+ "label": "4. Database worker",
+ "sublabel": "Retries failed writes",
+ "pos": [
+ 580,
+ 240
+ ],
+ "size": [
+ 164,
+ 72
+ ],
+ "sources": [
+ {
+ "path": "internal/messaging/reader.go",
+ "line": 114,
+ "end_line": 123
+ },
+ {
+ "path": "internal/messaging/process.go",
+ "line": 14,
+ "end_line": 30
+ },
+ {
+ "path": "internal/messaging/process.go",
+ "line": 65,
+ "end_line": 100
+ }
+ ]
+ },
+ {
+ "id": "row",
+ "type": "database",
+ "label": "5. PostgreSQL",
+ "sublabel": "One row per tenant + ID",
+ "pos": [
+ 310,
+ 240
+ ],
+ "size": [
+ 164,
+ 72
+ ],
+ "sources": [
+ {
+ "path": "internal/persistence/events.go",
+ "line": 22,
+ "end_line": 39
+ },
+ {
+ "path": "migrations/showcase/000001_events.up.sql",
+ "line": 2,
+ "end_line": 11
+ }
+ ]
+ }
+ ],
+ "connections": [
+ {
+ "id": "send",
+ "from": "application",
+ "to": "endpoint",
+ "label": "HTTPS + key",
+ "variant": "security"
+ },
+ {
+ "id": "enqueue",
+ "from": "endpoint",
+ "to": "queue",
+ "label": "Append event"
+ },
+ {
+ "id": "read",
+ "from": "queue",
+ "to": "worker",
+ "label": "Read later",
+ "variant": "dashed"
+ },
+ {
+ "id": "store",
+ "from": "worker",
+ "to": "row",
+ "label": "Batch INSERT"
+ }
+ ],
+ "cards": [
+ {
+ "dot": "cyan",
+ "title": "What the response means",
+ "items": [
+ "HTTP 202 follows queue acknowledgement. The database worker runs separately."
+ ]
+ },
+ {
+ "dot": "amber",
+ "title": "While PostgreSQL is down",
+ "items": [
+ "The worker retries. Queued events depend on retained data and surviving disks."
+ ]
+ }
+ ]
+}
diff --git a/docs/figures/render_story_guides.py b/docs/figures/render_story_guides.py
new file mode 100644
index 0000000..a0e5af1
--- /dev/null
+++ b/docs/figures/render_story_guides.py
@@ -0,0 +1,131 @@
+"""Phone reading guides for the two source-backed event-story diagrams.
+
+These explain the same responsibilities as event-journey.architecture.json and
+worker-replay.sequence.json. They are teaching views, not measured packet traces.
+Runtime source: 799106aeed58f6618bdc4b3711a84e11000fb0b5.
+"""
+
+from html import escape
+from pathlib import Path
+
+STYLE = """"""
+
+
+def text(x, y, label, kind="copy"):
+ return f'{escape(label)}'
+
+
+def page(title, description, height, parts):
+ return "\n".join(
+ [
+ f'",
+ "",
+ ]
+ )
+
+
+def arrow(start, end, label):
+ return [
+ f'',
+ f'',
+ text(194, (start + end) // 2 + 4, label, "small"),
+ ]
+
+
+def journey():
+ parts = [
+ text(20, 34, "Follow one event", "title"),
+ text(20, 61, "Keep the same event ID on retry.", "copy"),
+ ]
+ rows = [
+ ("1. Your application", "Saves the ID and event body."),
+ ("2. HTTPS endpoint", "Caddy and Go check the request."),
+ ("3. Redpanda queue", "Holds the event for the worker."),
+ ("4. Database worker", "Retries when a write fails."),
+ ("5. PostgreSQL", "One row per tenant + event ID."),
+ ]
+ labels = ["send", "append", "read later", "save"]
+ for i, (heading, body) in enumerate(rows):
+ y = 90 + i * 112
+ parts += [
+ f'',
+ text(36, y + 29, heading, "heading"),
+ text(36, y + 57, body),
+ ]
+ if i < 4:
+ parts += arrow(y + 80, y + 108, labels[i])
+ parts += [
+ text(20, 659, "202 confirms queue acceptance.", "copy"),
+ text(20, 685, "The database write runs separately.", "copy"),
+ text(20, 724, "Queue recovery needs retained data and disks.", "small"),
+ text(20, 746, "Source 799106a; full diagram linked.", "small"),
+ ]
+ return page(
+ "From one event to a saved row",
+ "The application sends a saved event ID over HTTPS. Redpanda holds it while a worker saves a PostgreSQL row.",
+ 770,
+ parts,
+ )
+
+
+def replay():
+ parts = [
+ text(20, 34, "One row after a restart", "title"),
+ text(20, 63, "The worker saves the row first.", "copy"),
+ ]
+ for y, heading, lines in [
+ (
+ 96,
+ "Before the crash",
+ [
+ "PostgreSQL has the saved row.",
+ "The queue position is not saved.",
+ "The worker stops here.",
+ ],
+ ),
+ (
+ 350,
+ "After restart",
+ [
+ "The worker reads the same ID.",
+ "PostgreSQL keeps the existing row.",
+ "The worker saves its queue position.",
+ ],
+ ),
+ ]:
+ parts += [
+ f'',
+ text(36, y + 34, heading, "heading"),
+ ]
+ parts += [text(36, y + 74 + i * 30, line) for i, line in enumerate(lines)]
+ parts += arrow(286, 338, "restart")
+ parts += [
+ text(20, 576, "Unique key: tenant + event ID.", "copy"),
+ text(20, 605, "A repeat does not update the saved content.", "small"),
+ text(20, 640, "Source 799106a; full sequence linked.", "small"),
+ ]
+ return page(
+ "A replay keeps the existing row",
+ "After a worker stops between SQL commit and queue-position commit, the same event is read again. Its unique key keeps one row.",
+ 664,
+ parts,
+ )
+
+
+if __name__ == "__main__":
+ output = Path(__file__).resolve().parents[1] / "assets"
+ (output / "event-journey-mobile.svg").write_text(journey())
+ (output / "worker-replay-mobile.svg").write_text(replay())
diff --git a/docs/figures/story-verification.json b/docs/figures/story-verification.json
new file mode 100644
index 0000000..623c0e1
--- /dev/null
+++ b/docs/figures/story-verification.json
@@ -0,0 +1,44 @@
+{
+ "schema": 1,
+ "runtime_source_revision": "799106aeed58f6618bdc4b3711a84e11000fb0b5",
+ "archify_version": "3.2.0",
+ "scope": "Logical event journey and the deterministic worker SQL-commit/read-position gap. Phone SVGs are reading guides, not additional packet traces. No new timing measurements.",
+ "native_export_sha256_before_whitespace_cleanup": {
+ "event-journey.svg": "d9579bd689877bffd1618ac05816423821d29619e5e053064c3edb2729387cf9",
+ "worker-replay.svg": "0a34c3ce3ab9c82cdfcee99c2c35886c5c510ed25bf9e88c0c0dd9eaeb907cc1"
+ },
+ "export_cleanup": "Only trailing source whitespace was trimmed; XML elements/attributes, visible labels and CSS tokens were checked unchanged.",
+ "assets_sha256": {
+ "worker-replay.svg": "9a62c01f33ff94b851a8600495dbc9539178e6ac90a63e27008eabec5d66624c",
+ "worker-replay-mobile.svg": "60c217e551a4607ff0eef8a75aa141213825ff4a6111418e5c1f6af3630c55da",
+ "event-journey-mobile.svg": "629b1c2d66492fe323b45a059e97b4b8b3b5fa2ed13d3567582670fdd2838f8d",
+ "event-journey.svg": "dfca99dd66b31acb36729b92a242558d40a1eaedc5656577f1ff97b3af82df5c"
+ },
+ "checks": {
+ "archify_validate_deliver_check_browser_check": "passed for both native diagrams",
+ "native_light_dark_visual_review": true,
+ "rendered_reader_pages": 19,
+ "desktop_content_width_pixels": 800,
+ "phone_viewport_pixels": 390,
+ "phone_document_scroll_width_pixels": 390,
+ "broken_images": 0,
+ "phone_guide_clipped_labels": 0,
+ "local_links_checked": 153,
+ "original_command_blocks_preserved": "Original commands retained; four first-run examples now reload the generated key, and one duplicate configuration block is omitted.",
+ "measured_result_tables_unchanged": true,
+ "previous_figure_and_study_index_hashes_unchanged": true,
+ "both_study_audits": "99 database / 33 pipeline / 9 recovery runs, 9 limited cases each; passed",
+ "auditor_unit_tests": 6,
+ "reader_review": "One fresh read-only editor/fact review; key handoff and two pending-count meanings corrected.",
+ "first_run_key_setup": "All four example environment blocks failed after the deployment unset, then passed after explicit key loading, using generated private configuration and the actual Python client constructor."
+ },
+ "source_spec_sha256": {
+ "docs/figures/event-journey.architecture.json": "ef9bfa1b5b6cb3bbf748c43d783e7d799a0535362a3a4fa794ea14f980bcb806",
+ "docs/figures/worker-replay.sequence.json": "6b64f98e7000134bf828af10221bae4e50cfc4797672c1d4d715941c7c3918ec"
+ },
+ "guide_script_sha256": "ac41d8ccd485e8afe2928dde01783f380b4a220a6acee92e8e07aaf66b73c9ca",
+ "native_artifact_sha256": {
+ "journey": "408b8b503a3aee4f91fd733d2af35c57a77d3429009673ccce9e99a962cc7bb9",
+ "replay": "2629c9edf11b9fbf21830affa35b9d4840d4e58b3c8bf6693e4a2f6db9d372ca"
+ }
+}
diff --git a/docs/figures/worker-replay.sequence.json b/docs/figures/worker-replay.sequence.json
new file mode 100644
index 0000000..06e5e13
--- /dev/null
+++ b/docs/figures/worker-replay.sequence.json
@@ -0,0 +1,146 @@
+{
+ "schema_version": 1,
+ "diagram_type": "sequence",
+ "meta": {
+ "title": "A worker crash can replay an event without adding a row",
+ "locale": "en",
+ "output": ".archify/sequence-worker-replay-20261104-123448/worker-replay.html",
+ "quality_profile": "showcase",
+ "repository": {
+ "url": "git@github.com:feat7/ingestkit.git",
+ "revision": "799106aeed58f6618bdc4b3711a84e11000fb0b5",
+ "link_mode": "local-only"
+ },
+ "legend": {
+ "mode": "hidden"
+ }
+ },
+ "participants": [
+ {
+ "id": "queue",
+ "type": "messagebus",
+ "label": "Queue",
+ "sublabel": "Redpanda",
+ "sources": [
+ {
+ "path": "internal/messaging/reader.go",
+ "line": 118,
+ "end_line": 141
+ }
+ ]
+ },
+ {
+ "id": "worker",
+ "type": "backend",
+ "label": "Worker",
+ "sublabel": "Go consumer",
+ "sources": [
+ {
+ "path": "internal/messaging/process.go",
+ "line": 14,
+ "end_line": 30
+ },
+ {
+ "path": "internal/messaging/failure_integration_test.go",
+ "line": 81,
+ "end_line": 155
+ }
+ ]
+ },
+ {
+ "id": "database",
+ "type": "database",
+ "label": "Database",
+ "sublabel": "PostgreSQL",
+ "sources": [
+ {
+ "path": "internal/persistence/events.go",
+ "line": 22,
+ "end_line": 39
+ },
+ {
+ "path": "migrations/showcase/000001_events.up.sql",
+ "line": 2,
+ "end_line": 11
+ }
+ ]
+ }
+ ],
+ "segments": [
+ {
+ "from": 140,
+ "to": 340,
+ "label": "Before the crash"
+ },
+ {
+ "from": 370,
+ "to": 650,
+ "label": "After the worker restarts"
+ }
+ ],
+ "messages": [
+ {
+ "id": "first-read",
+ "from": "queue",
+ "to": "worker",
+ "y": 170,
+ "label": "Read event"
+ },
+ {
+ "id": "first-write",
+ "from": "worker",
+ "to": "database",
+ "y": 210,
+ "label": "Save event",
+ "variant": "emphasis"
+ },
+ {
+ "id": "first-commit",
+ "from": "database",
+ "to": "worker",
+ "y": 250,
+ "label": "Commit: one row",
+ "variant": "return",
+ "note": "Worker stops before saving its queue position."
+ },
+ {
+ "id": "replay",
+ "from": "queue",
+ "to": "worker",
+ "y": 400,
+ "label": "Read same event again"
+ },
+ {
+ "id": "second-write",
+ "from": "worker",
+ "to": "database",
+ "y": 445,
+ "label": "Same event ID",
+ "variant": "emphasis"
+ },
+ {
+ "id": "duplicate",
+ "from": "database",
+ "to": "worker",
+ "y": 490,
+ "label": "Still one row",
+ "variant": "return",
+ "note": "The unique tenant + event ID key ignores this repeat."
+ },
+ {
+ "id": "position",
+ "from": "worker",
+ "to": "queue",
+ "y": 590,
+ "label": "Save read position"
+ },
+ {
+ "id": "position-ok",
+ "from": "queue",
+ "to": "worker",
+ "y": 630,
+ "label": "Position saved",
+ "variant": "return"
+ }
+ ]
+}
diff --git a/docs/integration.md b/docs/integration.md
index 843887e..b96ad89 100644
--- a/docs/integration.md
+++ b/docs/integration.md
@@ -1,19 +1,52 @@
-# Use IngestKit from a backend
+# Send events from your application
+
+Deploy the [collector](../deploy/README.md), then call it over HTTPS from your
+backend. The [API reference](api.md) describes the request and response. You can
+copy either helper into your project; they need no SDK installation or Go runtime.
+Use Python 3.9+ or Node 20+.
+
+Before choosing a client, decide where an unsent event will live. If your
+application already saves work and can retry it after a restart, the direct
+clients below can send that work. For an event that must be saved with a business
+change, use the [order/outbox example](../examples/outbox/README.md). It commits
+the order and its pending event together, then sends outside that transaction.
+A process can die between a standalone order commit and an HTTP call; retries
+alone cannot recover an event that was never saved.
+
+Keep keys on your backend. A browser or mobile app calls your backend, which
+chooses the event and its identity. The key selects the tenant; leave tenant ID
+out of the event body. During [key rotation](operations.md), both keys can point
+to that same tenant.
+
+## Try the included events
+
+From the collector checkout with its initial generated key mapping, run the
+following commands. They load the key again after the deployment demo clears it.
+Use your collector hostname in API_URL.
+For another backend host or a rotated key, supply `API_URL` and
+`INGESTKIT_API_KEY` through that application's private settings.
-Deploy the [self-contained server](../deploy/README.md), then send ordinary HTTPS
-requests. The [HTTP contract](api.md) is the interface; you can copy either small
-helper into your project without installing an SDK or running Go there. The
-Python example requires Python 3.9+; the Node example requires Node 20+.
+~~~sh
+export API_URL=https://events.example.com
+INGESTKIT_API_KEY=$(sed -n 's/^API_KEYS={"\([0-9a-f]*\)":"default"}/\1/p' deploy/.env)
+export INGESTKIT_API_KEY
+python3 examples/checkout/send.py
+SEND_MODE=single node examples/checkout/send.mjs
+~~~
+
+The two commands use the same three checkout UUIDs. Running either repeatedly
+still leaves three logical events for that tenant. `EVENTS_FILE` selects a JSON
+fixture with an `events` array; give new business events fresh UUIDs. The commands
+exit nonzero if the response is missing or its IDs do not match.
-Keep API keys on a trusted backend. Browser/mobile clients should call your own
-backend, which decides the event and supplies identity. Map overlapping keys to
-the same tenant during [key rotation](operations.md). Do not send a tenant ID in
-the event body.
+HTTP 202 means Redpanda accepted those IDs. It does not tell you whether the
+worker has finished the PostgreSQL write. Check SQL when your workflow needs
+that confirmation, and keep IDs/content after an uncertain response.
## Python
-From this checkout, the module can be imported directly. If copying the helper,
-change the import to `from ingest_client import Client, IngestError`.
+This import works from the repository. If you copy the helper into your project,
+use `from ingest_client import Client, IngestError` instead.
~~~python
import os
@@ -37,13 +70,14 @@ except IngestError as error:
raise
~~~
-Use `client.send_batch(events)` for a list. Both methods return the validated
-acknowledgement IDs. Construct the event once and retain it across retries.
+Create the event once, save it and reuse it on retry. Calling `client.send_batch(events)`
+sends a list; both methods return only the IDs whose response they have checked.
+Save the UUID along with the event body so a replacement process has the same work.
## Node
-Copy `examples/checkout/ingest-client.mjs` into your backend, or use this import
-when running a module from the repository root:
+Copy `examples/checkout/ingest-client.mjs` into your backend, or use the import
+below from a module in the repository root:
~~~js
import {randomUUID} from 'node:crypto';
@@ -71,50 +105,20 @@ try {
}
~~~
-Use `client.sendBatch(events)` for a list. Both modules serialize once per call,
-reuse identical bytes across bounded retries, validate acknowledgement IDs and
-leave the original event object unchanged. Keep event IDs and bodies when a
-process exits: an in-memory retry loop is not durable delivery.
+Use `client.sendBatch(events)` for a list. Both helpers serialize once per call,
+keep the original object unchanged, and resend identical bytes during their
+bounded retries. The application's saved event must also survive process exit;
+the client cannot recover an object that existed only in memory.
-## Try both callers
+## HTTPS trust and recovery
-After loading `INGESTKIT_API_KEY` as shown in the deployment guide:
-
-~~~sh
-export API_URL=https://events.example.com
-export INGESTKIT_API_KEY
-python3 examples/checkout/send.py
-SEND_MODE=single node examples/checkout/send.mjs
-~~~
+Public HTTPS uses the system's trusted certificate authorities. For your local
+test deployment, use `INGESTKIT_CA_FILE=/absolute/path/to/root.crt`, Python's
+`ca_file` option or Node's `caFile` option to trust its private CA. The helpers
+keep certificate verification enabled.
-Both use the same fixed checkout UUIDs, so running them repeatedly still stores
-three logical events for that tenant. Set `EVENTS_FILE` to your own JSON fixture
-with an `events` array, and use fresh UUIDs for new business events. The CLIs fail
-with a nonzero exit status when acknowledgement is absent or invalid.
-
-Public HTTPS uses the system CA roots. For an owned local deployment with a
-private CA, set `INGESTKIT_CA_FILE=/absolute/path/to/root.crt`; Python's `ca_file`
-and Node's `caFile` options provide the same trust. No certificate bypass is used.
-
-The [transactional outbox example](../examples/outbox/README.md) implements the
-order→dispatch→SQL workflow with SQLite, including a real after-ACK crash test.
-
-An HTTP send after committing your application's transaction still leaves a gap:
-the process can die between those operations. An application outbox closes that
-creation gap by saving the business row and serialized event in one local
-transaction, then dispatching it with stable IDs. The collector's deduplication
-handles dispatch retries; it does not make your application transaction and HTTP
-request atomic.
-
-## Choose a delivery boundary
-
-Use the direct clients when the application already retains work durably and can
-retry it, or when occasional loss before sending is acceptable for that event.
-Use an application outbox when creating the business state must also create
-pending delivery atomically. In both cases, keep UUIDs/content across uncertain
-responses; a matching 202 is broker acknowledgement, not a database query result.
-
-The [recovery captures](../benchmarks/results/selfhost-2026-11-04/README.md) include
-three broker-outage/outbox repetitions with 100 saved events each. The separate
-after-ACK child-kill regression checks the local marking gap exactly. The
-[delivery guide](delivery.md) explains the independent consumer SQL/offset gap.
+The outbox example includes a real crash test after HTTP acknowledgement but
+before the local pending row is updated. The [recovery study](../benchmarks/results/selfhost-2026-11-04/README.md)
+also runs a broker outage three times with 100 saved events each. These test
+different gaps: a local acknowledgement update, a queue outage, and the separate
+worker SQL/offset gap described in the [delivery guide](delivery.md).
diff --git a/docs/operations.md b/docs/operations.md
index cde933d..b4b4f44 100644
--- a/docs/operations.md
+++ b/docs/operations.md
@@ -1,7 +1,13 @@
-# Operating a single-host collector
+# Operate the collector
-Run these commands from the repository root. The helper consistently selects
-this deployment and its private configuration:
+Start here when an application got HTTP 202 but you cannot yet find the event
+in PostgreSQL. The API confirms that Redpanda accepted the event. Check the
+worker's progress to find out whether storage is catching up or stuck.
+
+## Check services, worker health and queued work
+
+Run from the repository root. The `dc` helper selects this deployment and its
+private configuration for every command:
~~~sh
dc() { docker compose --env-file deploy/.env -f deploy/compose.yml "$@"; }
@@ -11,18 +17,15 @@ dc exec -T redpanda rpk group describe ingestkit-consumer -X brokers=redpanda:90
dc exec -T consumer /consumer check
~~~
-API `/ready` checks broker acceptance. The consumer's private readiness check
-also requires database access and successful processing. A database Ping alone
-cannot clear a write, quarantine or offset-commit failure. Application logs emit
-an operation, error class, SQLSTATE when available, and source topic/partition/
-offset. Repeated failures of an operation are throttled for ten seconds; the
-next message reports the suppressed count. Recovery is logged once. Startup
-failures use partition/offset -1 because no source record exists yet. Raw error
-text, payloads, credentials and database URLs are excluded from these messages.
-Database and broker logs can contain data; inspect those privately when needed.
+API `/ready` checks whether the broker can accept writes. The consumer check
+also needs database access and successful processing. A database Ping proves
+connectivity, but cannot clear a failed write, quarantine operation or queue
+position update.
-Group lag shows queued broker records, not a durable count of business events.
-To inspect persisted events without retrieving payloads:
+The group command reports lag: queue records the consumer group has yet to
+handle. It is not a unique count of business events. Compare it with the stored
+row counts and latest insertion times below. The disk commands check space for
+the database and queue:
~~~sh
dc exec -T postgres psql -U ingestkit_admin -d ingestkit -c \
@@ -31,55 +34,66 @@ dc exec -T postgres df -h /var/lib/postgresql
dc exec -T redpanda df -h /var/lib/redpanda/data
~~~
-## Disk growth and retention
+Application logs name the operation and safe error class, add SQLSTATE when
+available, and identify the source topic, partition and offset. SQLSTATE is the
+database's error code; the source coordinates locate the queue record. Startup
+messages use partition/offset -1 when there is no record yet.
+
+Repeated failures for an operation are throttled for ten seconds. The next
+message reports how many were suppressed, and recovery is logged once. These
+messages exclude raw errors, event payloads, credentials and database URLs.
+Database and broker logs can contain data, so inspect them privately.
-The event log and quarantine topic retain records for seven days by default
-(`RETENTION_MS=604800000`). Kafka retention is asynchronous, not a storage quota.
-Keep enough free space for traffic bursts and an outage backlog; monitor both
-volumes, consumer lag and free disk. A long outage can exceed retention. Changing
-the environment alone does not change existing topics: explicitly apply the
-new retention value after deciding the required recovery window. For example,
-apply a fourteen-day window with:
+## Allow disk space for both the queue and the table
+
+The event and quarantine topics keep records for seven days by default,
+controlled by `RETENTION_MS=604800000`. Kafka removes old records asynchronously;
+retention is not a disk quota. Monitor free space in both volumes, consumer lag,
+traffic bursts and the backlog during an outage. An outage longer than the
+retained log can leave events unrecoverable.
+
+Editing the environment does not update an existing topic. To keep fourteen
+days of records, apply the setting to both topics:
~~~sh
dc exec -T redpanda rpk topic alter-config ingestkit.events ingestkit.dlq \
--set retention.ms=1209600000 -X brokers=redpanda:9092
~~~
-Set the same `RETENTION_MS=1209600000` in private configuration for future topic
-creation. PostgreSQL rows have no automatic
-expiry. Choose and test your own archival/deletion policy before continuous use.
-The collector does not protect against losing the single broker/database host.
+Also set `RETENTION_MS=1209600000` in private configuration for future topic
+creation. PostgreSQL rows do not expire automatically. Choose and test a database
+archive/deletion policy before running continuously. The single host provides
+no recovery from losing both its broker and database disks.
-## Rotate an API key
+## Replace an API key without changing the tenant
-Generate a fresh key with `openssl rand -hex 32` in a private terminal. Edit
-`deploy/.env` so `API_KEYS` temporarily maps both old and new keys to the same
-tenant. Keep it valid JSON on one line and retain mode 0600. Recreate the API:
+Generate a key with `openssl rand -hex 32` in a private terminal. In
+`deploy/.env`, temporarily map both the old and new key to the same tenant in
+`API_KEYS`. Keep the JSON on one line and the file mode at 0600. Recreate the API:
~~~sh
dc up -d --no-deps --force-recreate --wait api
~~~
-Move backend callers to the new key and verify acceptance. Remove the old key
-from the mapping and run the same command again. The old key should return 401;
-existing stored events remain under the tenant. A container restart does not
-reload configuration. Changing a tenant mapping changes identity; it is not key
-rotation. API keys authenticate trusted backend callers, so do not embed them
-in a browser or public mobile application.
+Move the backend callers to the new key and check that requests succeed. Then
+remove the old key and run the same command again. The old key should return
+401; existing events stay under the same tenant. A restart keeps the old
+environment, so configuration changes need recreation. Changing the tenant
+mapping changes identity instead of rotating a key. Keep keys out of browser
+and public mobile code.
-Admin database credentials are initialized when PostgreSQL first creates its
-data directory. Editing the initial password variable does not rotate an
-existing login. Plan a coordinated SQL password change and private configuration
-update if rotating database credentials. The writer role setup can update its
-password when deliberately recreated, followed by recreating the consumer; do
-not rotate it halfway through ingestion without expecting a temporary backlog.
+PostgreSQL's admin password is set when it first creates the data directory.
+Changing that initial environment variable does not change an existing login.
+To rotate database credentials, coordinate the SQL password change with private
+configuration. Deliberately recreating the writer-role setup can change that
+password; recreate the consumer afterward. Changing it during ingestion can
+cause a temporary backlog.
-## Back up and restore into a fresh target
+## Back up the saved rows
-A backup captures stored events at its snapshot. HTTP 202 may refer to events
-still in the broker, so it is not proof they are in the dump. Keep the private
-configuration separately and protect both backups from public access.
+A database dump contains rows committed at its snapshot. Events acknowledged
+with 202 may still be in Redpanda and absent from the dump. Protect backups from
+public access and keep a separate private copy of the deployment configuration.
~~~sh
umask 077
@@ -87,10 +101,12 @@ mkdir -p backups
dc exec -T postgres pg_dump -U ingestkit_admin -d ingestkit -Fc > backups/ingestkit.dump
~~~
-Restore into a **new empty deployment**, retaining the original until the new
-one is verified. Use a separate checkout/configuration and Compose project name,
-with a different hostname or the original gateway stopped during cutover. On the
-new host/check-out, define a helper for the replacement project:
+## Restore into a new empty deployment
+
+Keep the original deployment until the replacement is verified. Use a separate
+checkout, configuration and Compose project name. Give it another hostname, or
+stop the old gateway during cutover. Copy the dump to the replacement's private
+`backups/` directory, then define its helper and run:
~~~sh
newdc() { docker compose -p ingestkit-replacement --env-file deploy/.env -f deploy/compose.yml "$@"; }
@@ -104,48 +120,50 @@ newdc run --rm roles
newdc up -d --build --wait
~~~
-Copy the dump into the replacement's private `backups/` directory first. These
-commands assume the replacement database has never been migrated or populated;
-`pg_restore` must fail on conflicts. The dump carries the migration ledger and
-table ACLs. The restore needs the writer role to exist before restoring its ACLs:
-the commands create it using the replacement's admin session before
-`pg_restore`; the `roles` service then sets its private
-password and required privileges. Do not use `--clean`, drop schemas or delete
-volumes on the live source. The integration test exercises a separately owned
-empty replacement and verifies restored IDs, payload content, and subsequent
-new/duplicate event ingestion while the source remains intact.
-
-After restoring an older database while retaining an existing broker, its
-consumer group may already have committed past records missing from that
-snapshot. Stopping the consumer and planning a replay is essential: use a fresh
-consumer group from the earliest retained offsets. Stop the consumer with
-`dc stop consumer`, add a fresh `CONSUMER_GROUP=ingestkit-replay-UNIQUE` in the
-private configuration, and recreate it with
-`dc up -d --no-deps --force-recreate --wait consumer`. The reader starts a new
-group at the earliest retained offset. Keep the replacement group name after
-verification. An alternative is an explicitly reviewed offset reset while the
-consumer is stopped. Replayed IDs deduplicate
-against restored rows. Retention expiry or broker disk loss can make the gap
-unrecoverable. Never reset an active group or assume database restore rewinds
-broker offsets. A new empty broker has no queued events from the old host.
-
-## Upgrade and shut down
-
-Read the migration and dependency changes, make a backup, and test the target
-revision against a disposable restore first. Pull the chosen revision, then run
-`dc up -d --build --wait`. Keep compatible images and the previous revision for
-investigation; reverting code does not reverse database migrations or broker
-format changes. Review those before planning a rollback.
-
-Use `dc down` for shutdown. Named database, broker and certificate volumes remain.
-Do not use `down -v`, global prune, or volume removal for routine operations.
-
-## What the recovery evidence covers
-
-The [corrected availability captures](../benchmarks/results/selfhost-2026-11-04/README.md)
-retain three repetitions each for a database outage, consumer kill/restart and
-application-outbox replay while the broker is unavailable. They reconcile accepted
-IDs/content and record actual control times. A start command returning is not a
-claim that the group has caught up; check readiness, lag and the stored UUIDs.
-SQL-unavailable intervals remain observation gaps. These local tests do not
-establish tolerance of host/disk loss or an outage beyond retained data.
+The replacement database must never have been migrated or populated. The restore
+must fail on conflicts. The dump contains the migration ledger and table access
+rules, so the writer role must exist before `pg_restore` restores those rules.
+The commands create it with the replacement admin login; the `roles` service then
+sets its private password and required privileges.
+
+Keep `--clean`, schema drops and volume deletion away from the live source.
+The integration test restores into a separate empty project and checks IDs,
+payload content and new/duplicate ingestion while preserving the source.
+
+## Fill the gap between an older backup and the queue
+
+Restoring PostgreSQL does not rewind the worker's saved queue position. If the
+broker is retained, its consumer group may already be past events missing from
+the older snapshot. Stop the consumer and plan replay from the earliest retained
+records with a fresh consumer group.
+
+Use `dc stop consumer`, set a new `CONSUMER_GROUP=ingestkit-replay-UNIQUE` in private
+configuration, then run `dc up -d --no-deps --force-recreate --wait consumer`.
+A new group starts at the earliest retained offset. Keep that replacement group
+name after checking the rows. Repeated event IDs are ignored against restored
+rows. A separately reviewed offset reset while the worker is stopped is another
+option; never reset an active group.
+
+Retention expiry or broker disk loss can leave a gap that replay cannot fill.
+A new empty broker contains none of the old host's pending events.
+
+## Upgrade or shut down
+
+Read the migration/dependency changes, make a backup and test the target revision
+against a disposable restore. Pull that revision and run `dc up -d --build --wait`.
+Keep compatible images and the previous revision for investigation. A code revert
+does not reverse a database migration or broker format change; review those before
+planning a rollback.
+
+Use `dc down` to stop. Named database, broker and certificate volumes remain.
+Routine shutdown does not need `down -v`, global prune or volume removal.
+
+## What the recovery tests establish
+
+The [recorded recovery experiments](../benchmarks/results/selfhost-2026-11-04/README.md)
+run a database outage, worker kill/restart and broker-outage/outbox retry three
+times each. They check accepted IDs and content and retain actual control times.
+A completed start command does not prove the consumer group has caught up:
+check readiness, lag and stored UUIDs. SQL observation gaps remain gaps. The
+experiments do not establish recovery from host/disk loss or an outage beyond
+retained history.
diff --git a/docs/superpowers/publication/2026-11-03-launch-drafts.md b/docs/superpowers/publication/2026-11-03-launch-drafts.md
index 5a22943..8ae2a3f 100644
--- a/docs/superpowers/publication/2026-11-03-launch-drafts.md
+++ b/docs/superpowers/publication/2026-11-03-launch-drafts.md
@@ -1,78 +1,81 @@
-# Publication drafts — updated 4 November 2026
+# Publication drafts (updated 4 November 2026)
-These are local drafts. No article, repository release or social submission has
-been published by this work. Check that the reviewed branch and referenced source
-commits are available publicly before using these links. Add personal context only
-if it happened; do not invent adoption, company impact or popularity.
+Choose a blog home before posting the article. These drafts do not publish it,
+create a release or submit anything to social sites. Check public code/results
+links before posting. Add personal context only when it happened; the repository
+does not establish adoption, company impact or popularity.
## Article
-Title: Building an event collector around the failure boundaries
+Title: What happens after an event collector says "accepted"?
-Alternative: What HTTP 202 means in a self-hosted event pipeline
+Alternative: Keeping an event through a database outage and a worker restart
-Source: [publication-ready Markdown draft](../../article.md). Choose the author's
-canonical blog home, replace relative code/results/image links with public URLs,
-and preview the responsive figures on that platform. Keep the measured revision,
-three-repetition ranges, unknown deliveries and shared-host caveats beside claims.
-If cross-posting, retain one canonical article URL rather than splitting the story
-across competing copies. No hosting destination is selected or created here.
+The [article draft](../../article.md) follows an order event from the application
+to PostgreSQL, then explains the retry gaps and the write-method experiment.
+Replace relative code/results/image links with public URLs for the chosen blog,
+and check its image rendering on a phone. Keep the measured revision, all three
+runs, uncertain outcomes and shared-host limits beside the claims. If cross-posting,
+choose one canonical article URL.
-The concrete hook: a deployable collector plus an application outbox, two separate
-crash windows, and evidence that changed the default from COPY/staging/merge to
-batch INSERT. The value is being able to run, break and inspect it.
+The story has a runnable deployment, an application outbox and two tested crash
+gaps. The database experiment also changed the implementation: batched INSERT
+replaced COPY/staging/merge after the measured comparison.
-## Regular Hacker News article submission
+## Hacker News article submission
-Title: Building an event collector and testing its failure boundaries
+Title: What happens after an event collector says "accepted"?
URL: the final public article URL.
Optional author comment:
-> I built a small Go/Redpanda/PostgreSQL event collector with a self-contained
-> HTTPS deployment and a runnable transactional-outbox example. The repo tests
-> crashes after SQL commit and after HTTP acknowledgement, then reconciles the
-> same event IDs. A corrected 25-case study favored batch INSERT over my COPY/merge
-> path by median, so I changed the default and reran it. All repetitions and limits
-> remain in the captures, including ambiguous deliveries; these are local results,
-> not maximum-capacity claims. I'd welcome feedback on the failure model and method.
+> I built a small Go event collector with an HTTPS API, Redpanda queue and
+> PostgreSQL store. The article follows an order event through a database outage
+> and two crash gaps. The repo includes a Docker Compose deployment and a small
+> order/outbox app you can run. Tests stop the worker after SQL commit and stop
+> the sender after HTTP acknowledgement, then check the stored IDs. A 25-case
+> study found a lower median for batch INSERT than for my COPY/merge path in
+> all 11 database configurations, so I changed the writer and ran the study
+> again. The results include all runs and unknown deliveries. I'd welcome
+> feedback on the retry behavior and experiment design.
-A blog post belongs in a regular submission. The [Show HN guidelines](https://news.ycombinator.com/showhn.html)
-reserve Show HN for something people can try, rather than reading material.
+Use a regular submission for the article. [Show HN](https://news.ycombinator.com/showhn.html)
+is for a project readers can try.
-## Potential separate Show HN
+## Separate Show HN submission
-Title: Show HN: IngestKit – a self-hosted event collector with crash/replay tests
+Title: Show HN: IngestKit, a self-hosted event collector with crash/replay tests
-URL: the public repository after this branch is made available.
+URL: the public repository containing the reviewed code.
Description draft:
-> Deploy a small HTTPS event collector with Docker Compose, send stable UUIDs from
-> Python or Node, and inspect PostgreSQL storage. The application outbox persists
-> orders and pending events atomically and replays the same IDs after a dispatcher
-> crash. Local demos and real-service tests stop dependencies and check accepted
-> IDs, stored content and source progress. Deployment builds Go inside Docker;
-> owned local demos/studies require Go. It is one host with finite retention, not HA.
+> Run an HTTPS event collector with Docker Compose, send events from Python or
+> Node, and find the rows in PostgreSQL. The included order/outbox app saves
+> orders and pending events together, then resends the same IDs after a crash.
+> Demos and real-service tests stop dependencies and check which events reached
+> storage. Go builds inside Docker on the deployment host; local demos and
+> studies need Go installed. The server uses one host with finite queue retention.
-Use only when readers can actually access and run the reviewed code. Prefer one
-focused submission at a time; this file does not authorize posting, messaging,
-vote coordination or account/hosting setup.
+Use this only when the reviewed code is publicly accessible and runnable.
+Submit one focused story at a time. Posting, messages, vote coordination and
+hosting/account setup need their own explicit request.
-## Resume / project description
+## Resume or project description
-Built a self-hosted Go event collector with HTTPS, Redpanda buffering and
-PostgreSQL storage; supplied copyable Python/Node clients and a transactional
-outbox. Verified tenant-scoped deduplication and crash replay with real dependency
-outages, restricted-role/restore tests and a reproducible 25-configuration study.
-Changed the default SQL writer based on measured batch/payload/duplicate results.
+Built a self-hosted Go event collector with HTTPS, a Redpanda queue and PostgreSQL
+storage, plus reusable Python/Node clients and a durable application outbox.
+Tested database outages, writer permissions, restore and crashes during retry;
+verified that replay kept one row per tenant/event ID. Ran 25 controlled experiment
+configurations and changed the SQL writer based on the batch, payload and
+repeated-ID results.
Short bullet:
-Built and failure-tested a self-hosted Go/Redpanda/PostgreSQL collector with HTTPS,
-durable application outbox and replay-safe storage; recorded 25 reproducible
-experiment configurations with raw samples, ID reconciliation and explicit limits.
+Built and tested a Go/Redpanda/PostgreSQL event collector with a Docker Compose
+HTTPS deployment and durable outbox; verified crash replay and recorded 25
+experiment configurations with raw samples and explicit limits.
-No claim of production adoption, business impact, cloud cost, maximum throughput
-or popularity is supported by the local repository evidence.
+These local results do not support a claim of production adoption, business
+impact, cloud cost, maximum throughput or popularity.
diff --git a/examples/README.md b/examples/README.md
index dcae4a3..2193d16 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -1,15 +1,15 @@
-# Application examples
+# Try the application examples
-- [Checkout](checkout/README.md): copyable Python/Node HTTP clients, single/batch
- fixture CLIs, explicit CA trust and bounded stable-ID retries.
-- [Transactional outbox](outbox/README.md): atomically store a business order and
- serialized event, then dispatch safely across process restarts.
-- [Backend integration guide](../docs/integration.md): import and use the clients
- from application code.
-- [HTTP contract](../docs/api.md): limits, responses, retries and persistence checks.
+Start with the [self-hosted deployment](../deploy/README.md), then choose an
+example. Neither requires Go in the application or a package-registry SDK.
-Start with the [self-hosted deployment](../deploy/README.md); the application
-examples do not require Go or a package registry SDK.
+- [Checkout](checkout/README.md) sends three events using the Python or Node
+ client. Run it twice to see the same IDs produce one set of rows.
+- [Order and outbox](outbox/README.md) saves an order and pending event together,
+ then sends pending work from a separate process. Restart it to retry saved IDs.
-A 202 acknowledges the broker. Verify storage separately when your workflow
-requires it. Keep API keys in your backend and retain event IDs across restarts.
+The [integration guide](../docs/integration.md) shows the imports to use in your
+own backend. The [API reference](../docs/api.md) lists fields, limits and retries.
+
+Keep the key on your backend and keep event IDs across restarts. HTTP 202 confirms
+queue acceptance; use SQL to confirm storage when your workflow needs it.
diff --git a/examples/checkout/README.md b/examples/checkout/README.md
index bd8e54c..5816c93 100644
--- a/examples/checkout/README.md
+++ b/examples/checkout/README.md
@@ -1,49 +1,57 @@
-# Checkout events
+# Send three checkout events
-Three ordinary envelopes describe a product view, checkout start and completed
-order. The fixed UUIDs make retry/deduplication easy to observe.
+The fixture has a product view, checkout start and completed order. Each has a
+fixed UUID, so you can resend it and see PostgreSQL keep one row per event.
-For a deployed collector, follow the [server setup](../../deploy/README.md), load
-its backend key and set the URL:
+Follow the [server setup](../../deploy/README.md), then run from that checkout
+with its initial generated key mapping. The commands reload the key after the
+deployment demo clears it. On another backend host or after rotating the key,
+supply API_URL and INGESTKIT_API_KEY through private application settings.
+Use your collector hostname in API_URL.
~~~sh
export API_URL=https://events.example.com
+INGESTKIT_API_KEY=$(sed -n 's/^API_KEYS={"\([0-9a-f]*\)":"default"}/\1/p' deploy/.env)
export INGESTKIT_API_KEY
python3 examples/checkout/send.py
SEND_MODE=single node examples/checkout/send.mjs
~~~
-These read `events.json` and retain its IDs on retry. Running both repeatedly
-still stores three logical events for that tenant. Use fresh explicit UUIDs for
-new business events. Both default to the batch endpoint; `SEND_MODE=single` sends
-individual requests and `EVENTS_FILE=/path/to/events.json` selects your own
-`{ "events": [...] }` fixture. A 202 acknowledges the broker, not PostgreSQL.
+Both commands read `events.json` and keep those IDs on retry. Running them again
+still leaves three logical events for that tenant. Give new business events
+fresh UUIDs. The clients use the batch endpoint by default; `SEND_MODE=single`
+sends individual requests. `EVENTS_FILE=/path/to/events.json` selects another
+`{ "events": [...] }` fixture. HTTP 202 confirms that the queue accepted the
+records; the worker writes PostgreSQL separately.
-For an isolated local walkthrough with Docker and Go:
+## Run a disposable local demo
+
+With Docker and Go installed:
~~~sh
make demo DEMO_FLAGS=-cleanup
make demo-recovery DEMO_FLAGS=-cleanup
~~~
-Each owns its services and checks accepted/stored IDs. Omitting `-cleanup` stops
-its services and preserves volumes; the command prints its exact cleanup recipe.
-The root `make up` development stack also supports the callers' local defaults,
-including `local-demo-key`; those defaults are not deployed credentials.
+Each demo creates its own services and checks that accepted IDs reached storage.
+Without `-cleanup`, it stops those services and keeps their volumes, then prints
+the command for removing that run. The root `make up` development stack also
+works with the callers' local defaults, including `local-demo-key`. Use the generated
+private key for the deployed server.
-## Copy the client into an application
+## Use the same helper in your backend
-`ingest_client.py` exports `Client.send` / `Client.send_batch` and `IngestError`.
-`ingest-client.mjs` exports `IngestClient.send` / `sendBatch` and `IngestError`.
-The modules perform no work at import time and have no package dependencies.
-See the [backend guide](../../docs/integration.md) for imports and usage, and the
-[API contract](../../docs/api.md) for acknowledgement and retry rules.
+`ingest_client.py` exports `Client.send`, `Client.send_batch` and `IngestError`.
+`ingest-client.mjs` exports `IngestClient.send`, `sendBatch` and `IngestError`.
+Importing either module does no I/O, and neither needs third-party packages.
+The [integration guide](../../docs/integration.md) shows imports and calls; the
+[API reference](../../docs/api.md) explains response checking and retry decisions.
-For the self-hosted HTTPS deployment, set API_URL and INGESTKIT_API_KEY. Public
-certificates use normal system trust. `INGESTKIT_CA_FILE` selects an explicit
-private CA for local tests; neither helper disables certificate checks.
+Set API_URL and INGESTKIT_API_KEY for your HTTPS deployment. Public certificates
+use system trust. For local tests, `INGESTKIT_CA_FILE` names a private CA to trust.
+Both helpers leave certificate checks enabled.
-Run their controlled-server tests (including TLS and interrupted requests):
+Run the client tests, including TLS and interrupted requests:
~~~sh
python3 -m unittest discover -s examples/checkout -p 'test_*.py'
diff --git a/examples/outbox/README.md b/examples/outbox/README.md
index 86b3c38..8046d1c 100644
--- a/examples/outbox/README.md
+++ b/examples/outbox/README.md
@@ -1,16 +1,19 @@
-# Checkout with a transactional outbox
+# Save an order and its event together
-This is one small SQLite application, not another collector service. Creating an
-order saves its business row and serialized event in the same transaction. A
-separate, bounded dispatch command sends pending events through the reusable
-Python HTTP client. The collector still acknowledges the broker before storage.
+This example is a small SQLite application. One transaction saves an order and
+a pending event containing its UUID and exact JSON body. A separate dispatch
+command sends pending events to IngestKit. If either process stops, the saved
+event is still available for a later attempt.
-From the repository root, with the HTTPS collector deployed and its backend key
-loaded as described in the [deployment guide](../../deploy/README.md):
+Follow the [deployment guide](../../deploy/README.md), then run from that checkout
+with its initial generated key mapping. These commands reload the key. On another
+backend host or after key rotation, supply API_URL and INGESTKIT_API_KEY through
+private application settings. Use your collector hostname in API_URL:
~~~sh
umask 077
export API_URL=https://events.example.com
+INGESTKIT_API_KEY=$(sed -n 's/^API_KEYS={"\([0-9a-f]*\)":"default"}/\1/p' deploy/.env)
export INGESTKIT_API_KEY
python3 -m examples.outbox create-order --database private/orders.db \
--order-id order-123 --amount-cents 2500
@@ -19,52 +22,56 @@ python3 -m examples.outbox dispatch --database private/orders.db
python3 -m examples.outbox status --database private/orders.db
~~~
-The first command prints its persisted event UUID. Repeating the same order ID
-and amount returns that UUID; a conflicting amount fails. The UUID, occurred_at
-and serialized payload do not change when the process restarts. Use a new order
-ID for a new order. The private directory and SQLite business data belong on a
-persistent disk and in your own application backup strategy.
+The create-order command prints the event UUID. Creating that order again with
+the same amount returns the same UUID; a conflicting amount fails. Restarting
+the process leaves the UUID, occurred_at and serialized payload unchanged. Use
+a new order ID for a new order. Keep the private directory on persistent disk
+and include this SQLite business data in your application's backup plan.
-`dispatch` attempts at most 100 pending records once, with bounded retries inside
-the HTTP helper. `--batch-size 10` lowers the selection size; `--max-attempts 1`
-limits transport attempts. Set `INGESTKIT_CA_FILE` when using an explicit local
-CA. Public HTTPS uses ordinary certificate verification.
+## Read the dispatch result
-The command prints attempted/acknowledged/rejected counts and the remaining
-pending count. It exits nonzero when the selected work could not be acknowledged
-or was rejected. An empty queue exits successfully. States mean:
+`dispatch` selects at most 100 pending records per invocation. The HTTP helper
+makes bounded retries for that work. `--batch-size 10` lowers the selection size;
+`--max-attempts 1` allows one transport attempt. Set `INGESTKIT_CA_FILE` for an
+explicit local CA. Public HTTPS uses ordinary certificate verification.
-| State | Meaning |
+The command prints attempted, acknowledged and rejected counts, plus the number
+still pending. It exits nonzero if selected work was rejected or could not be
+acknowledged. An empty queue succeeds.
+
+| State | What it means |
| --- | --- |
-| pending | Still needs broker acknowledgement; network ambiguity, authentication/configuration failures and server errors remain here |
-| acknowledged | HTTP 202 with exactly the selected IDs; PostgreSQL may still be catching up |
-| rejected | A 400/413 requires an operator decision; the event and safe error code remain inspectable |
+| pending | The event still needs queue acknowledgement. Network uncertainty, authentication/configuration failures and server errors leave it here. |
+| acknowledged | HTTP 202 named exactly the selected IDs. PostgreSQL may still be catching up. |
+| rejected | A 400/413 needs an operator decision. The saved event and safe error code remain available. |
+
+`status` prints counts and a bounded list of problem IDs, attempts and safe error
+codes. An attempt counts a dispatcher call, not every internal HTTP retry.
+Error summaries exclude payloads, keys, response bodies and database URLs.
+
+Inspect rejected events and decide whether to fix input, split a batch, retry
+or compensate for a business operation. The example has no automatic rejection
+reset, since rewriting an event that might already have arrived needs a decision.
-`status` reports all state counts and a bounded list of problem IDs, attempts and
-safe error codes. Attempts count dispatcher calls, not each internal HTTP retry.
-No payload, key, response body or database URL is copied into error summaries.
-Do not silently discard a rejected event. Decide whether to repair the business
-input, split an oversized batch, retry, or compensate. This example deliberately
-has no automatic rejection reset that could rewrite an already delivered event.
+## If dispatch stops after HTTP 202
-## The crash boundary
+The dispatcher reads pending work, closes the SQLite connection and sends HTTP.
+Only after checking the response IDs does it mark those rows acknowledged in a
+new transaction. It holds no business write lock during the network wait.
-The dispatcher reads pending work, releases the SQLite connection, sends HTTP,
-and only then marks the selected rows acknowledged in another transaction. It
-holds no business write lock while waiting on the network. If it dies after the
-broker ACK but before that update, the rows remain pending. The next process
-resends their original IDs and content; PostgreSQL keeps one row per tenant/ID.
-The integration test pauses a test-only wrapper precisely after a real ACK,
-kills that child process, dispatches again and checks one stored row.
+If the process stops after the response but before that update, the row stays
+pending. A new process sends the same UUID and content again. PostgreSQL's unique
+tenant/event key keeps one row. The integration test pauses a separate test-only
+wrapper after an actual acknowledgement, kills it, dispatches again and checks
+that single row.
-Run one dispatcher at a time. Adapting this to multiple dispatchers needs a lease
-or claim protocol in your application's database; this example does not claim
-that behavior. A timer/cron/application worker can invoke the one-shot command,
-but deploy that scheduling only after choosing your application's lifecycle.
+Run one dispatcher at a time. Multiple dispatchers need a claim or lease in your
+application database. A timer, cron job or application worker can invoke this
+one-shot command once you have chosen how it fits your application's lifecycle.
-## Verify at the collector
+## Check the row at the collector
-Copy the created event UUID into this query on the collector host:
+Copy the created UUID into this query on the collector host:
~~~sh
docker compose --env-file deploy/.env -f deploy/compose.yml exec -T postgres \
@@ -72,16 +79,18 @@ docker compose --env-file deploy/.env -f deploy/compose.yml exec -T postgres \
"SELECT event_id,event_type,payload FROM ingestkit.events WHERE tenant_id='default' AND event_id='YOUR-EVENT-UUID';"
~~~
-The payload includes the order ID and amount. Acknowledged outbox state alone
-does not replace this persistence check.
+Check the order ID and amount in the payload. An acknowledged outbox row confirms
+queue acceptance; it does not replace this storage check.
+
+## Adapt it to your database
+
+Put the business write and serialized outbox row in the same database transaction.
+Keep the ID stable, send outside that transaction and mark acknowledgement after
+validating the response. A separate business commit followed by HTTP still leaves
+a gap where the process can die before creating any pending delivery.
-To adapt the pattern, place your real business write and the serialized outbox
-row inside the same database transaction. Keep the event ID stable, dispatch
-outside the transaction, and mark acknowledgement only after validating the
-response. An HTTP call after a standalone business commit leaves a creation gap
-that retries alone cannot repair. SQLite here is a concrete teaching example;
-you do not need another SQLite database when your application already uses
-PostgreSQL or another transactional store.
+Use your application's existing transactional database when you have one. SQLite
+is here to make the example runnable; it is not a requirement for other projects.
~~~sh
python3 -m unittest discover -s examples/outbox -p 'test_*.py'
@@ -90,7 +99,7 @@ scripts/test-integration.sh -run TestOutbox -v
~~~
The [recorded recovery study](../../benchmarks/results/selfhost-2026-11-04/README.md)
-uses 100 saved events per repetition and a broker outage longer than the publish
-deadline. It retains pending state and replays from a new dispatcher. This is
-separate from the deterministic after-ACK kill check described above; neither
-replaces your own application database's transaction/worker design.
+also tests 100 saved events per run during a broker outage longer than the publish
+deadline. A new dispatcher resends the pending events. That outage test is separate
+from the exact after-ACK kill test, and both supplement the transaction/worker
+checks needed for your own application.