Architecture decisions¶
Decisions that shape how the backend, warehouse-service, payment-service, notification-service, delivery-service and llm-service work together. delivery-service and llm-service follow the existing decisions (ADR 1, 4 and 12 for delivery-service; ADR 9's "Rust is the baseline" for both) and have their own contracts (DELIVERY_SERVICE_CONTRACT.md, LLM_SERVICE_CONTRACT.md). Each record states the context, the decision and what follows from it. A superseded decision stays in this file with its status changed.
| ADR | Decision | Status | Since |
|---|---|---|---|
| 1 | Internal integration via a pull event feed | Accepted; reversed for stock by ADR 6 | backend 3.16.0, warehouse-service 1.3.0, payment-service 1.1.0 |
| 2 | Backend keeps a fulfilment read model | Accepted | backend 3.11.0, warehouse-service 1.0.0 |
| 3 | Outbox and feed consumer implementations stay per service | Accepted | warehouse-service 1.0.0, payment-service 1.0.0 |
| 4 | Database per service on one PostgreSQL server | Accepted | backend 3.12.0, warehouse-service 1.0.0 |
| 5 | Notifications move out of the backend | Accepted | backend 3.21.0, notification-service 1.0.0 |
| 6 | warehouse-service owns the stock ledger | Accepted | backend 3.22.0, warehouse-service 1.6.0 |
| 7 | A broker transport next to the event feed | Superseded by ADR 12 | backend 3.23.0, warehouse-service 1.7.0, payment-service 1.4.0, notification-service 1.1.0 |
| 8 | The services and the Ollama mock run Rust ports | Accepted | warehouse-, payment-, notification-service and ollama-mock -rs 1.0.0 |
| 9 | The backend runs its Rust port; Rust is the baseline | Accepted | backend-rs 1.0.0 |
| 10 | No metrics stack in production | Accepted | December 2026 |
| 11 | A local-only documentation assistant | Accepted | docs-rag-rs 0.2.3 (opt-in docker-compose.rag.yml) |
| 12 | The feed is the only event transport; Artemis carries only emails | Accepted; supersedes ADR 7 | backend-rs 1.4.0, warehouse-, payment-, notification-service-rs 1.3.0, delivery-service-rs 1.2.0 |
ADR 1: Internal integration via a pull event feed¶
Status: accepted, November 2026 (backend 3.16.0, warehouse-service 1.3.0, payment-service 1.1.0). Reversed for stock only by ADR 6: the backend calls warehouse-service for stock commands. ADR 7 let the same events also travel through Artemis; ADR 12 made the feed the only transport again.
Context¶
Up to backend 3.15.0 the backend was a synchronous hub. warehouse-service and
payment-service called its internal API, and the backend in turn called
payment-service: card refunds went from a backend outbox
(payment_refund_outbox) to POST /internal/v1/payments/refunds. That made a
cycle (backend → payment-service → backend): both services had to be up
and configured with each other's address (PAYMENT_BASE_URL), a
payment-service release could break the backend's refund delivery, and the
backend carried retry and error-mapping code for a service it does not own.
Customer cancellations reached warehouse-service only through a reconciler that
polled order snapshots every minute.
The backend already publishes a CommerceEvent for every order change. The
full profile runs ActiveMQ Artemis, but the lightweight student profile and the
aitesters-backend sandbox on the server run without a broker, and their
memory budget has no room for one.
Decision¶
The backend records every domain event in a domain_events table in the same
transaction as the state change and serves it as an HTTP pull feed,
GET /internal/v1/events?after&limit&types, authenticated with the existing
service tokens. Consumers poll it, keep their own cursor and deduplicate by
event id. Card refunds become card-refund.requested events; the backend makes
no outbound call to either service. The contract is in
EVENT_FEED.md.
ActiveMQ was rejected because the profiles that need the integration most (the lightweight classroom profile and the aitesters sandbox) have no broker, and a broker would add a container, memory and a new failure mode to every profile. The feed reuses what every profile already has: PostgreSQL and HTTP.
Consequences¶
- Dependencies only point to the backend: warehouse-service → backend and
payment-service → backend. The backend can start, run and be released without
either service;
PAYMENT_BASE_URLis gone from every Compose file and the release check now requires its absence. - Delivery is at-least-once with idempotent consumers. Latency is up to one poll interval (5 s) from a cancellation to a refunded card or a cancelled shipment, instead of the next outbox or reconciler run. (Until backend 3.24.0 a 3 s settle delay came on top; the feed now serves events in commit order instead, see EVENT_FEED.md.)
- The backend stores events for 30 days (
events.retention). A consumer down for longer misses events; warehouse-service keeps its reconciler (now every 10 minutes) as a safety net, and refunds stay capped by the backend'scard_refund_requests. - The backend does not learn whether a refund was carried out; payment-service logs refunds it rejects. Testers check refunds through the payment API.
- New consumers can subscribe to any recorded type without a backend change.
card-refund.requestedis internal and never offered to user webhooks.
ADR 2: Backend keeps a fulfilment read model¶
Status: accepted (backend 3.11.0, warehouse-service 1.0.0); confirmed with ADR 1.
Context¶
warehouse-service owns shipments, but the backend stores a copy of their
progress in orders.fulfilment_state (NONE, AWAITING_PICK, PICKED,
PACKED, SHIPPED, DELIVERED, CANCELLED). With the event feed in place
the question was whether the backend should drop that duplicated state and ask
warehouse-service instead.
Decision¶
The backend keeps fulfilmentState as a read model that warehouse-service
updates synchronously with PUT /internal/v1/orders/{id}/fulfilment.
- Order reads stay local. The order JSON (
GET /api/v1/orders/{id}, order lists, the internal order snapshot) includesfulfilmentStatewithout the backend calling warehouse-service, which would bring back the dependency ADR 1 removed. - The cancel/ship race is decided in one place. A customer may cancel only
while the state is
NONEorAWAITING_PICK. Because warehouse-service moves the state forward with a synchronous PUT before it confirms a pick, the backend's row lock decides whether the cancellation or the pick wins; the loser gets 409. An asynchronous copy could let both succeed. - Consistency is restored automatically. The feed delivers
order.cancelledto warehouse-service within seconds, and the reconciler (every 10 minutes) cancels or adopts shipments the feed did not cover. - Split shipments keep one state (warehouse-service 1.5.0). An order can
ship as several parcels from different warehouse locations, but the backend
still sees one forward-only
fulfilmentState. warehouse-service mirrors the aggregatemax(last mirrored, aggregate), where the aggregate isAWAITING_PICKwhile every parcel awaits pick and otherwisemax(PICKED, min over the non-cancelled parcels). So the first pick moves the order toPICKED(from then on the customer can no longer cancel), and the order isSHIPPEDorDELIVEREDonly when every parcel is. The backend is unchanged and the cancel/ship race still has one decider: the first parcel's pick takes the order row lock exactly like a single shipment's.GET /api/v1/warehouse/reconciliationlists orders whose parcels disagree with the backend's state.
Consequences¶
- The same state lives in two places and the rules that keep it in step
(forward-only steps, repeat is a no-op,
CANCELLEDonly through a cancellation) are part of the warehouse contract. - The synchronous PUT means a pick, pack or ship needs the backend to be up; warehouse-service answers 503 otherwise.
- With split shipments the backend's state is a summary: per-parcel progress
(
GET /api/v1/orders/{id}/shipments) is read from warehouse-service.
ADR 3: Outbox and feed consumer implementations stay per service¶
Status: accepted.
Context¶
The backend (email_event, webhook_deliveries until 3.20.x), warehouse-service
(notification_outbox), payment-service (payment_outbox) and
notification-service (notification_emails, webhook_deliveries) each have a
transactional outbox, and from ADR 1 the three services each have an event
feed consumer. The code is similar, so a shared library was
considered.
Decision¶
Each service keeps its own implementation. There is no shared library:
- the services are released independently, each from its own repository with its own image; a shared artifact would couple their release cycles and force coordinated upgrades for an internal refactoring;
- there is no artifact repository to publish an internal library to, and copying source between repositories is no better than owning it;
- the code is small (a table, a scheduled dispatcher, a backoff function) and each service's error handling differs (a 409 to a payment capture voids the payment; a 503 to a notification is retried; other rejections are final).
The shared behaviour is a convention, documented here and checked in each service's own tests.
Outbox convention¶
| Aspect | Convention |
|---|---|
| Write | The outbox row is inserted in the same transaction as the business change; a requestId (UUID) is the idempotency key the receiver deduplicates on |
| Send | Right after the commit, then by a scheduled retry job (warehouse and payment: every PT30S) |
| Backoff | 30 seconds after the first failure, doubling per attempt, capped at 30 minutes; at most 10 attempts |
| Retryable | Only "receiver unavailable" answers are retried (warehouse notifications: 503; payment results: any 5xx and I/O errors); every other rejection is final at once and handled by the service (for example a 409 to a capture voids the payment) |
| Row state | attempts, next_attempt_at, sent_at, last_error. A row is pending while sent_at is null and attempts is below the maximum, sent once sent_at is set, and given up when attempts reaches the maximum |
| Payload | Stored once and resent byte for byte (and re-signed where signed) |
| Metrics | <service>.outbox.pending (gauge, <service>_outbox_pending in Prometheus) in warehouse-service 1.5.0, payment-service 1.3.0 and notification-service 1.0.0 (webhook deliveries plus queued emails); a counter of rows given up, when added, is <service>.outbox.failed |
The backend's own outboxes predate this convention and keep their documented
policies (EmailRetryJob: backoff 1, 2, 4, 8 minutes, five attempts;
webhook_deliveries: PENDING → DELIVERED or FAILED, 1, 2, 4… minutes,
eight attempts).
Feed consumer convention¶
event_cursors (one row per consumer) and processed_events (handled event
ids), one local transaction per event that locks the cursor row, skips known
ids, applies the change, records the id and advances the cursor; transient
errors stop the run without moving the cursor, non-transient ones are logged
and skipped. See EVENT_FEED.md.
Consequences¶
- A behaviour change to the convention is made in every service separately and recorded here first.
- Reviews compare a new outbox or consumer against this table.
ADR 4: Database per service on one PostgreSQL server¶
Status: accepted (backend 3.12.0 moved every profile to PostgreSQL; warehouse-service 1.0.0 and payment-service 1.0.0 got their own schemas).
Context¶
Each service must own its data: no service may read another's tables, and migrations must be independent. A separate PostgreSQL server per service would give the strongest isolation, but the production VPS has 1 vCPU and about 4 GiB of memory for two sites (stable and aitesters), and the lightweight profile has to run on student laptops.
Decision¶
One PostgreSQL server per site (16, then 19 from December 2026), one database, and per service a schema
owned by its own role: public for the backend, warehouse, payment
and notification for the services. The one-shot postgres-roles container
(postgres/service-roles.sh) creates each role with
LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION, makes it the owner of
its schema only and grants CONNECT on the database. Services connect with
currentSchema=<schema> and run their own Flyway history in it.
Consequences¶
- Isolation is verified, not assumed. A service role cannot read the
backend's
publictables, create objects inpublicor use the other service's schema; the productionverifyAnsible role checks each of these after every deploy, andscripts/verify-release-images.pychecks that each service uses its own role, schema and env file. - Memory. One server (
shared_buffers=32MB,max_connections=40) fits in 256 MiB in the lightweight profile, and the sandbox server in 160 MiB; the services use Hikari pools of at most three connections. Three servers would roughly triple the fixed cost per site. - Shared fate. The services share the server's availability, backups and restore: one encrypted backup covers all schemas, and a restore rolls all of them back together (which is also the rollback procedure for a release that migrates several schemas).
- Cross-schema joins are impossible by design; warehouse-service keeps snapshots (order id, owner, prices) instead of foreign keys.
ADR 5: Notifications move out of the backend¶
Status: accepted, November 2026 (backend 3.21.0, notification-service 1.0.0).
Context¶
Up to 3.20.x the backend rendered and sent every customer email and delivered
user webhooks: a dispatcher, a retry job and the webhook_deliveries outbox
ran inside the process that also serves orders, payments results and the
event feed. A slow webhook receiver or a broker outage competed with checkout
for threads and connections, and every change to a template or to the webhook
retry policy was a backend release, with the l20 course regression run that
goes with it. Both features only react to commerce events the backend
already records in its feed (ADR 1).
Decision¶
A new service, notification-service (port 4005, schema and role
notification), owns user webhooks and commerce emails as an event-feed
consumer:
- The backend records
notification.requested(template, recipient, properties,requestId) where it used to send a commerce email, whenNOTIFICATIONS_DELIVERY=feed; defaultemailkeeps the old behaviour. WEBHOOKS_ENABLED=falsestops the backend's dispatcher and retry job; the endpoints stay mapped but the gateway sends that traffic to notification-service, which serves the same public API.- A one-time import (
GET /internal/v1/webhooks/export, only for theNOTIFICATIONcaller) moves subscriptions and inboxes with their ids and secrets. - Account emails (password reset,
POST /api/v1/email, email events) stay in the backend: they are part of the l20 course contract and are not commerce reactions.
Every profile that runs notification-service sets feed and webhooks off; the
l20 compatibility stack runs the backends without notification-service, with
the defaults.
Consequences¶
- The backend makes no outbound notification call; a receiver or broker outage
delays emails and deliveries in notification-service's outboxes
(
notification_outbox_pending) without touching checkout. - Webhook deliveries and commerce emails leave up to one poll interval (5 s) after the change instead of right after the commit. The delivery body is byte-compatible, so receivers notice only the latency.
- One more container per site: 160 MiB limit each (see the memory budget in ANSIBLE.md) and a fourth database role per site.
- Webhook signing secrets are encrypted with notification-service's own key instead of the backend's MFA key; losing the key makes stored secrets unreadable, so it lives in Vault next to the other service secrets.
- The feed now has three consumers; a new event type needs no backend change to reach a user webhook once notification-service lists it.
ADR 6: warehouse-service owns the stock ledger¶
Status: accepted, November 2026 (backend 3.22.0, warehouse-service 1.6.0). Contract: INVENTORY_OWNERSHIP_CONTRACT.md.
Context¶
Stock had two writers. The backend kept products.stock_quantity and the
inventory_movements ledger, while warehouse-service, which receives
purchases and restocks returns, had to call the backend's internal receipts API
to change stock it physically handles. Stock is a warehouse concern, and a
second writer made every warehouse change a backend change.
Decision¶
- warehouse-service owns stock: quantities (
stock_items), movements and checkout reservations live in its schema. - The backend keeps a projection:
products.stock_quantitybecomes a read copy, updated from warehouse-service's answers and from its stock-level push (POST /internal/v1/inventory/levels, applied only when the per-productledgerVersionis newer). Catalog, search, the cart and the admin stock levels stay local and keep working without warehouse-service; the movement history is read from warehouse-service. - Commands are synchronous, backend → warehouse: checkout reservations,
admin and GraphQL/gRPC adjustments, initial stock and product deletes call
WAREHOUSE_URLwithAuthorization: Bearer BACKEND_SERVICE_TOKEN(connect 2 s, read 5 s). If warehouse-service is unreachable, slow or failing, the public call answers503 {"message":"Inventory service unavailable"}. - This reverses ADR 1 for stock only. Every other integration still points
to the backend, and the backend still publishes cancellations through the
event feed (stock restores travel there as
stockRestore).
Consequences¶
- The backend now depends on warehouse-service at run time for checkout and
stock writes, but not at start-up: warehouse-service needs the backend's JWKS,
so the backend must never
depends_onwarehouse-service in Compose. Until warehouse-service is healthy, stock commands answer 503. - A command whose answer is lost (timeout) can leave a reservation without an order; warehouse-service's reaper releases it after two minutes, asking the backend first. Product creation and deletion go through a backend outbox, so they never fail on warehouse-service.
- The projection is eventually consistent: a warehouse-only change (receipt,
restock, cancel restore) reaches it after the push, and
stock_outbox_pendingshows the backlog. The fault-injection lab'swarehouse-down,warehouse-slowandbackend-down warehouseexercises show all three effects. - One more secret per site (
backend_service_token,aitesters_backend_service_token), and the course compatibility stack runs a warehouse-service next to each backend.
ADR 7: A broker transport next to the event feed¶
Status: superseded by ADR 12
in December 2026. Accepted in November 2026 (backend 3.23.0, warehouse-service 1.7.0,
payment-service 1.4.0, notification-service 1.1.0). Its contract page,
EVENT_BROKER_CONTRACT.md, was removed with the transport; it stays in the
repository's history.
Context¶
ADR 1 chose a pull feed over ActiveMQ because the lightweight classroom profile
and the aitesters sandbox had no broker. Since then the stack became the base of
a course on testing distributed systems, and the feed hides the failure modes
that course is about: there is no queue to watch, no redelivery, and a poison
event is logged and skipped, so it is simply gone. Meanwhile the production
server already runs Artemis for the email queue, and a broker costs the
lightweight profile about 300–400 MiB only when a student asks for it.
Decision¶
- One contract, two transports. The events, their JSON and their ids stay
exactly those of the feed. Each service chooses at run time with
EVENTS_TRANSPORT=feed|broker; the native images contain both paths. - The outbox stays the source of truth.
domain_eventsis already written in the transaction of the change. A relay in the backend publishes the rows it has not published yet (published_at, migration V27) in one transacted JMS session and then marks them, so delivery is at least once and a crash can only duplicate, never lose. Change data capture (Debezium) was rejected as too heavy for the lab. - Topology in the broker's configuration, not in code. One multicast
address per site (
awesome.commerce.events,aitesters.commerce.events), one durable queue per consuming service filtered on the event type, and one dead-letter queue per consumer queue, all declared inartemis/commerce-events.propertiesso the queues exist before the first publish (a multicast address without queues drops messages). - Failures go back to the broker. A consumer handles each message in a transacted session; any exception rolls it back, Artemis redelivers it with backoff and dead-letters it after five attempts. The feed poller's "log and skip" does not exist in broker mode.
- The feed stays. It is the default, the course compatibility stack and the
replay path. Profiles: full and both production sites use
broker; lightweight usesfeedunlessdocker-compose.broker.ymlis added.
Consequences¶
- The backend still calls no consumer, and consumers still depend only on the
backend, now plus the broker. Checkout never waits for the broker: while
Artemis is unreachable the relay's backlog grows (
events_relay_pending) and drains afterwards. - Latency from a cancellation to its effect drops from up to 5 seconds (the poll interval) to about one second (the relay interval).
- Ordering is per order (message groups), and only while nothing is being redelivered: a redelivery delay lets later events of the same order overtake the failed one. Consumers therefore deduplicate by event id only and no longer trust the feed cursor's sequence order in broker mode.
- New operational surface: the broker topology file, broker credentials for
every service (
SPRING_ARTEMIS_USER/_PASSWORDfrom Vault on the server), dead letters someone has to look at (scripts/broker dlq), and an Ansible check that every queue has its consumer. - The fault-injection lab gains
broker-down,broker-slowandpartition-broker, and broker exercises.
ADR 8: The services and the Ollama mock run Rust ports¶
Status: accepted, 29 November 2026.
Context¶
warehouse-, payment- and notification-service were GraalVM native Spring Boot images of about 440 MB each, using 55–85 MiB under load; the Ollama mock was a JVM Spring Boot image of about 500 MB using about 250 MiB. The VPS has about 4.25 GiB of RAM for two full sites.
Decision¶
Replace all four with Rust ports (*-rs repositories, axum and sqlx) that keep
everything another component observes: HTTP routes, status codes and bodies,
the database schemas with identical Flyway history, service tokens,
environment variables, event feed and broker queues. The ports talk to
Artemis over AMQP 1.0 on the same acceptor (no Rust client speaks the Artemis
core protocol). The backend stays Java.
Consequences¶
- About 400 MiB less memory and 1.55 GB less image data for the four services; the e2e suite's duration did not change, because the backend bounds it.
- Rollback is a re-pin to the last Java images; the schema is shared, so no restore is needed in either direction.
- JVM metrics and Java security mounts no longer apply to these services; payment- and notification-service images have no shell, so their healthchecks run the binary.
- Verified with each port's tests, the Java repositories' contract scripts, the full e2e suite (827/827) and the l20 course gate (190/190).
ADR 9: The backend runs its Rust port; Rust is the baseline¶
Status: accepted, 1 December 2026.
Context¶
After ADR 8, the Java backend (a GraalVM native image of about 600 MB using 100–200 MiB) was the last Java service on the request path. It also bounded the e2e suite's duration.
Decision¶
Run backend-rs (axum, sqlx, async-graphql, tonic). It keeps everything another
component or the course observes:
- the REST, GraphQL and gRPC APIs, status codes and error bodies;
- the database schema and Flyway history;
- JWT signing keys, refresh tokens and MFA secrets;
- the event feed and broker queues;
- the intentional course bugs.
The Rust repositories are the products from now on. Each one is verified by its
own tests, the e2e suite and the l20 course gate, not by comparison with Java.
The Java repositories are archived once production has run on Rust for a while.
(Done: by December 2026 every Java repository of the stack is retired, and the
consumer runs consumer-rs.)
Consequences¶
- All five services use about 39 MiB instead of about 555 MiB. The e2e suite runs in 3.4 instead of 4.4 minutes.
- Rollback is a re-pin to
backend:3.25.2with its-Xmxarguments, and the schema is shared. - JVM-only actuator endpoints (
env,beans,threaddump, …) answer 404, and no JVM metrics are published. - Verified with the parity harness (about 5,070 checks), the e2e suite (827/827), the l20 course gate (190/190) and the broker check.
ADR 10: No metrics stack in production¶
Status: accepted, 1 December 2026.
Context¶
After lean phases A and B, production still ran Prometheus, Alertmanager, Node Exporter and Blackbox Exporter (about 150 MiB in use, 768 MiB of limits) for alerts the host watchdog already sends. Nobody used the Prometheus UI. The owner monitors their sites with Waitcher. All services are Rust binaries using a few MiB each, so JVM heap alerts no longer apply.
Decision¶
Remove the metrics stack from production and from the local profiles,
including the k6 overlay with Grafana and InfluxDB:
- The host watchdog keeps reporting container, OOM, disk, memory and backup
problems to Telegram.
- Waitcher checks both sites from outside (home page, /actuator/health, TLS)
and receives the watchdog's heartbeat as the dead-man check.
- The services keep /actuator/prometheus for ad-hoc reads and the labs.
Consequences¶
- No metric history, latency percentiles or warning-tier alerts.
- Capacity questions use
docker statsandfreeon the host. - The public checks now run from outside the VPS, so a dead VPS is detected.
- Restoring metrics later means adding an overlay back. The service endpoints are unchanged.
Reservations saga (note)¶
Backend 3.21.0 lets a PENDING order's stock hold expire
(reservationExpiresAt, default 30 minutes). This is a small saga across
the services, coordinated by events and by the order's row lock, with no
distributed transaction:
- Order created: stock deducted (
ORDER_DEDUCTED), the hold starts. - Either payment-service captures the card and the backend marks the order
PAID, orReservationExpiryJobcancels it first (order.cancelledwithreason = "RESERVATION_EXPIRED"plusorder.reservation-expired; compensation: stockORDER_RESTORED, coupon released, gift-card and points tenders returned). - The row lock on the order decides a race. A capture that arrives after the
expiry gets 409 and payment-service voids the payment (the existing
"not payable" compensation); payment-service also refuses to start a
payment for a snapshot whose
reservationExpiresAthas passed. - warehouse-service never sees an expired order (only
PAIDorders are released); notification-service tells subscribers.
There is no grace period: the fault-injection lab's "payment settles after the reservation expired" exercise (FAULT_INJECTION_LAB.md) shows the void.
Follow-ups¶
- A GET that mutated state — resolved in warehouse-service 1.3.1.
GET /api/v1/warehouse/shipments/{id}used to cancel anAWAITING_PICKshipment when it found the order cancelled on the backend ("reconcile on read"). A safe method that changes data surprises caches, retries and testers, so 1.3.1 makes the read side-effect free and does not call the backend;order.cancelledarrives through the event feed within seconds and the reconciler covers the rest. The refused-transition path (409 "Order was cancelled by the customer" on pick/pack/ship) stays.
ADR 11: A local-only documentation assistant¶
Status: accepted, December 2026 (docs-rag-rs 0.2.3, opt-in overlay
docker-compose.rag.yml). Revised the same month: the first build, a PostgreSQL index with our
own retrieval loop (0.1.0), was replaced by Claude Code over plain files after the evaluation
below. See Docs assistant for how to run it.
Context¶
The documentation of the stack is spread over this repository and the repositories of every
service:
- here: docs/, docs-site/, the README and the Compose files;
- in the services: READMEs, contracts, OpenAPI specs, contributor guides, and the code itself.
Students ask the same questions about it again and again: which profile runs what, how an order travels through warehouse, payment and notification, what a contract field means. An assistant that answers from these repositories, with citations, helps them. The course also needs a realistic LLM feature to test: - groundedness and citations; - refusals; - prompt injection through indexed content.
Constraints: - The production server has one vCPU and anonymous public traffic. A service that spends money per question would need rate limiting, a budget cap and a key on the server. - Anthropic offers no embeddings API. - The stack's repositories are about 1,500 text files and 13 MB.
What was measured¶
The first build answered with a retrieval loop of our own: PostgreSQL full-text search, a
Messages API tool loop, and citation checking. A golden dataset of 77 questions was used to
compare four ways of answering with claude-sonnet-5-5:
- 36 held-out questions, written without seeing the retrieval code;
- 8 questions in Polish;
- 11 out of scope.
The full report:
| single search, one call | our tool loop | Claude Code over the files | whole corpus in the prompt | |
|---|---|---|---|---|
| In-scope correct | 68 % | 94 % | 88 % | 94 % |
| Polish questions correct | 1/7 | 6/7 | 6/7 | 6/7 |
| Multi-hop correct | 9/16 | 13/16 | 15/16 | 14/16 |
| Cost per question | $0.02 | $0.04 | $0.09 | $0.11, plus about $2 to write the cache |
- A single search is not enough. Searching once with the student's own words misses too often, above all in Polish.
- An agent that searches again is what works. Claude Code over plain files is as good as our own loop over a database, at about twice the cost and latency. It needs no index, no database and no retrieval code.
- The whole corpus in the prompt is not worth it. It is 780K tokens, about $2 before the first answer, and close to the context limit.
Decision¶
- Local only.
docs-ragruns only on a student's machine, as an opt-in Compose overlay (docker-compose.rag.yml). It is never part of the production Compose files, Ansible or the gateway; a contract script checks that. - A knowledge base of plain files.
docs-rag buildcopies every repository, whole, at the version the release train pins: - what goes in: documentation, specs and code;
- what stays out: secrets, binaries and files over 512 KB;
- two files are generated: an
INDEX.mdmap and asources.json; - the knowledge base is built in CI and baked into the image;
- there is no database and no index.
- The harness answers.
docs-rag askruns Claude Code headless (claude -p) in the knowledge base: - its tools are
Read,GrepandGlobonly; - for questions about behaviour it checks the code, cites it next to the documentation and flags where the two disagree (0.2.2: 60/66 correct at $0.05 a question);
- it starts from an empty environment, with the student's key, a fresh
HOMEand no CLAUDE.md or memory, under a per-answer budget cap.
The pinned Claude Code binary is in the image, checked against its release checksum.
- Bring your own key. The student sets ANTHROPIC_API_KEY in a git-ignored .env. The key
never goes into an image or a committed file. Without a key ask names the missing variable.
- Keyless tools and a mock mode.
- The MCP tools search_docs, read_document and list_sources need no key: a student's own
agent can reason over the same knowledge base.
- RAG_MODE=mock quotes the best matching lines instead of asking a model.
- CI never needs a key: tests use a fake claude and a fake Messages API.
- Mandatory citations and refusals. Every claim cites [repo/path@version] or
[repo/path#anchor@version].
- A citation holds only when it names a file at its version that the harness read or found.
Other citations are removed.
- An answer left without one becomes a refusal that names the repositories searched.
- Two interfaces: the CLI (docker compose run --rm docs-rag ask "...") and an MCP server
over stdio (docker compose run --rm -T docs-rag).
- Built to be tested.
- Every answer returns the documents consulted, the tool calls, token usage, cost and a trace
id.
- The golden dataset, an LLM judge checked against hand-labelled answers, and reports in the
repository measure correctness, faithfulness, citations, refusals, cost and latency.
Rejected: - Deploying it to production: a key on the server and anonymous spending behind it. - Our own retrieval over PostgreSQL: built, measured and replaced. It is no better than the harness and has more parts. - Embeddings and a vector database: a second model or a second key, and nothing measured calls for them. - The whole corpus in one prompt: about $2 per cold cache, and close to the context limit.
Consequences¶
- Students pay for their own questions, about $0.05 each. The production server, its memory budget and its secrets do not change.
- The image is large, about 520 MB unpacked, mostly the Claude Code binary, which ships with it.
- Releases. The knowledge base and the Claude Code version must be bumped with the release train, or answers describe old versions.
- Answers vary with the model and the harness version. Tests on real answers assert properties and thresholds over the golden dataset, not exact text.
- External calls. The stack gains a service that sends repository content to an external API. Credential-looking files are left out of the knowledge base.
ADR 12: The feed is the only event transport; Artemis carries only emails¶
Status: accepted, December 2026 (backend-rs 1.4.0, warehouse-service-rs, payment-service-rs and notification-service-rs 1.3.0, delivery-service-rs 1.2.0). Supersedes ADR 7.
Context¶
ADR 7 added the broker transport for a course on testing distributed systems. No part of a course uses it. What stayed was the cost of carrying every commerce event two ways:
- every service had a feed poller and a broker listener, two sets of tests and two sets of failure semantics;
- ordering differed: the feed is ordered by commit, the broker only per order and not during a redelivery;
- the backend ran an outbox relay, both sites needed a queue topology, broker credentials for every service, dead letters to watch, an Ansible queue check and an aitesters reset hook for Artemis' duplicate-ID cache.
Its one gain in production, about one second instead of up to five between a change and its effect, matters to none of the flows (refunds, webhooks, emails, deliveries, stock restores). The broker's other advantage, a dead-letter queue in place of the feed's "log and skip" for poison events, can live in the consumers' own databases.
Artemis itself was first added to the stack to carry emails, as a learning exercise, and it keeps that job.
Decision¶
- One transport. Every consumer reads the backend's feed
(EVENT_FEED.md). The backend's relay, the broker listeners,
EVENTS_TRANSPORT, the commerce queues anddocker-compose.broker.ymlare removed. - Poison events are parked, not lost. An event whose own content cannot be
handled is written to the consumer's
parked_eventstable with its data and the reason, recorded as processed, and passed. A database, backend or unexpected failure stops the run with the cursor unchanged, so the next poll retries it and nothing behind it is lost. - Artemis carries only the
emailqueue, from the backend and notification-service to the consumer, which delivers to Mailpit. - The retired queues and addresses are deleted from the production broker by the Ansible converge, which is idempotent.
Consequences¶
- An event takes effect within one poll interval (5 s) of its commit, on every profile.
- To handle a parked event again after a fix, delete its
processed_eventsrow and move the consumer's cursor back before itssequence; events already processed in between are skipped by id. - warehouse-, payment- and delivery-service need no broker credentials and no longer depend on Artemis. The lightweight profile, the course stack and production now run the same event path.
- The fault-injection lab keeps
broker-down,broker-slowandpartition-brokerfor the email path (backend and notification-service, full profile). domain_events.published_at(V27) stays, since applied migrations never change, but is no longer written.