84 KiB
Local deployment and Compose
This guide describes the checked-in configuration. Compose provides a local technical stack; it does not establish a production deployment.
Core application
Install Docker Engine and the Docker Compose plugin. At the repository root, copy .env.example to .env, replace every placeholder password, and keep the file local. Then run:
make -C deploy config
make -C deploy up
deploy/docker/docker-compose.yml starts PostgreSQL, Redis, SeaweedFS, Kafka, the Go backend, and the frontend container. Nginx in the frontend container serves static assets and proxies /api to Go. PostgreSQL, Redis, SeaweedFS, Kafka, Go, and Nginx communicate on the Compose network.
Before it opens its listeners, the backend applies the database migrations embedded in its binary; a migration error stops the container. Compose does not pass DATABASE_MIGRATE_ON_START, so the deployed backend always migrates at startup, and the PostgreSQL role in DATABASE_URL needs DDL rights on the application schema. That flag is a local development option; a separate least-privilege migration role is future work. Right after the migrations, and only when they run, the backend seeds the demo product policy: when the product policy family has no version, it publishes version 1 and logs demo product policy published; otherwise it logs that the seed was skipped and changes nothing. With DATABASE_MIGRATE_ON_START=false the seed is skipped too. A database error during the seed stops the container like a migration error. See DEVELOPMENT.md and ARCHITECTURE.md.
Consent texts are published by migrations, not at startup: migration 00009 publishes the demo texts c1-2026-10-01 to c5-2026-10-01 with kind demo. The database refuses to change or delete a published text, so a new text is a new version in a new migration, and the texts of the actual operator must be published that way before real personal data are accepted. An account with consent history cannot be deleted with a plain DELETE FROM users (SQLSTATE 23001 on consent_records_subject_id_fkey), and the consent records of a confirmed account cannot be deleted at all (SQLSTATE 23000, consent_records_retained); only the unverified account cleanup and the re-registration of an unverified account remove consent records. See ARCHITECTURE.md.
The backend build context is backend/, so Docker applies backend/.dockerignore. Local tools, caches, environment files, and build outputs are excluded from that context.
The current postgres:alpine volume mounts at /var/lib/postgresql; the image stores data in a subdirectory for its major version. When the tag advances to a new major version, migrate an existing database with pg_upgrade or backup/restore. Updating the image alone does not convert the data.
Open http://127.0.0.1:8080. The host port binds to loopback. Nginx handles /healthz, proxies /api/ to Go, and uses the SPA fallback for other paths. The public API health route is /api/v1/healthz through Nginx /api/. On the internal port 8080, Go also serves /healthz for the process and /readyz, which checks PostgreSQL with SELECT 1, Redis with PING, and the SeaweedFS bucket with HeadBucket; any dependency being unavailable produces 503. The internal backend port 9090 serves /metrics.
This Nginx configuration has no production TLS. The current bind does not expose the app directly to the public network. Remote access needs a selected TLS reverse proxy, firewall rules, and environment-specific configuration.
Useful commands:
make -C deploy config
make -C deploy up
make -C deploy logs
make -C deploy down
make -C deploy smoke
Redis uses redis:alpine, the REDIS_PASSWORD value from .env, and the internal redis:6379 address; it publishes no host port. Data is limited to 128 MB with allkeys-lru eviction, and the container memory limit is 256 MB. RDB and AOF are disabled with no persistent volume: restarting Redis clears the cache. Do not keep the only copy of a record there. The backend and Redis exporter both require its password.
Backend settings are REDIS_ADDR, REDIS_PASSWORD, REDIS_DB, and REDIS_TIMEOUT. Compose supplies redis:6379; a directly launched Go process defaults to localhost:6379, DB 0, and a 1s timeout. Provide a separately reachable Redis address for direct execution because the current Compose does not publish Redis outside its network.
SeaweedFS uses chrislusf/seaweedfs:latest with weed mini: master, volume, filer, and S3 API share one container. The named seaweedfs_data volume mounts at /data and preserves object content and metadata. S3 is reachable only inside the network at http://seaweedfs:8333, with no published host port. WebDAV, Admin UI, IAM API, Iceberg, and Lance are disabled. Nginx continues to serve the frontend and /api; there is no direct object route.
Set SEAWEEDFS_ACCESS_KEY and SEAWEEDFS_SECRET_KEY in .env, replacing the example values. Compose passes them to the server as AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY, and passes SEAWEEDFS_BUCKET as S3_BUCKET to initialize the bucket at startup. This is one administrative credential pair for the local stack, not production service-level access separation. Never provide it to browser clients.
SeaweedFS joins only the internal storage network (APP_STORAGE_NETWORK, by default <APP_PROJECT>_storage). The backend joins it and the default network; the monitoring Prometheus joins it to scrape port 9327, so start the core project before monitoring. No other container can resolve or reach SeaweedFS. This network is the primary control, because the container also serves filer, master, volume, and admin APIs and unauthenticated gRPC that ignore S3 credentials; see ARCHITECTURE.md for the list and the remaining risk. Do not add other services to the storage network.
The S3 credentials make S3 itself private: SeaweedFS answers unsigned S3 requests with 403, and Compose refuses to start with empty values because SeaweedFS without any identity accepts anonymous S3 requests. -s3.iam=false removes only the IAM management API. As defense in depth, the service entrypoint exports fresh random WEED_JWT_* signing keys at every start, so filer and volume HTTP requests need a token that never leaves the container, and -ip=127.0.0.1 with -whiteList=127.0.0.1,@ limits master and volume HTTP to in-container callers. The keys are not configuration and need no rotation; restarting the container replaces them. Smoke checks that the frontend cannot reach SeaweedFS by name or by its storage address, that S3 refuses an unsigned request, and that the filer, master, and volume HTTP APIs refuse a caller that is not inside the container.
The stack publishes no object URLs. The bucket has no public read policy or anonymous ACL, and the backend creates no public or presigned links; future downloads go through an authenticated backend endpoint that streams the file. Size and content type limits are per feature policy in backend/internal/usecase/files/ rather than deployment settings, so there is no extra environment variable. Keep the Nginx request body limit from the upload route aligned with the largest policy when such a route is added.
Backend settings are SEAWEEDFS_ENDPOINT, SEAWEEDFS_ACCESS_KEY, SEAWEEDFS_SECRET_KEY, SEAWEEDFS_BUCKET, SEAWEEDFS_REGION, and SEAWEEDFS_TIMEOUT. Compose supplies endpoint http://seaweedfs:8333; a directly launched Go process defaults to http://localhost:8333, bucket lincodex, region us-east-1, and timeout 10s. SEAWEEDFS_TIMEOUT bounds connection setup, the TLS handshake, the wait for response headers, and whole deletion and readiness calls; it does not bound object upload or download bodies, which follow the caller's context. Credentials are required. Direct execution needs a separately reachable private endpoint. Readiness checks the bucket; the backend does not create it.
Ordinary down preserves the SeaweedFS volume. Losing the volume loses both objects and metadata; prepare a verified backup before changing the image or deleting the volume. This is one node without HA, cross-node replication, or configured off-host backups.
Kafka uses the official apache/kafka:latest image as one KRaft node that combines the broker and controller roles; there is no ZooKeeper. Clients use the PLAINTEXT listener at kafka:9092, which is reachable only inside the Compose network and publishes no host port. The controller listener binds to 127.0.0.1:9093 inside the container, so other containers cannot reach it. The client listener has no TLS, authentication, or ACLs: any container attached to the Compose network, including monitoring services that join it, can produce and consume. Keep the network private and do not publish the port.
The named kafka_data volume mounts at /var/lib/kafka/data and stores topic logs, consumer offsets, and KRaft metadata, so events survive container restarts and an ordinary down. KAFKA_HEAP_OPTS bounds the JVM heap to -Xms256m -Xmx512m, and the container memory limit is 1 GB. The image's default JMX agent is disabled, so no JMX port is open. Topic data is kept for 7 days or up to 1 GiB per partition, whichever limit is reached first, in 128 MiB segments. Replication factors and the minimum in-sync replica count are 1 because there is one node. This node provides no HA or replication; losing the volume loses all events and consumer offsets.
KAFKA_CLUSTER_ID in .env is required. It identifies the KRaft cluster that formatted the volume. It is not a credential and grants no access, so .env.example contains a sample value. Generate your own value once before the first start:
docker run --rm apache/kafka:latest /opt/kafka/bin/kafka-storage.sh random-uuid
Changing the value after the volume is formatted stops Kafka from starting with that volume.
Automatic topic creation is disabled: writing to a missing topic fails instead of creating it. The backend creates its events topic itself (see Outbox relay); create any other topic explicitly. Kafka CLI tools inherit the broker's KAFKA_HEAP_OPTS, so give them a small heap when running them in the container. For example, a manual technical check with the default app project:
docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \
exec -e KAFKA_HEAP_OPTS=-Xmx128m kafka /opt/kafka/bin/kafka-topics.sh \
--bootstrap-server localhost:9092 --create --topic lincodex.technical.probe \
--partitions 1 --replication-factor 1
The Compose health check runs kafka-broker-api-versions.sh against localhost:9092, so Kafka is healthy only after the broker answers API requests. make -C deploy smoke waits for that health check together with the other core services; it does not check the relay or read events.
The backend receives KAFKA_BROKERS, a comma-separated list of host:port bootstrap addresses. Compose supplies kafka:9092; a directly launched Go process defaults to localhost:9092. An explicitly empty value, an empty list entry, a missing or zero port, or a URL scheme fails configuration. The outbox relay connects to these brokers in the background: the backend does not wait for Kafka at startup, and /readyz does not check Kafka. The advertised address kafka:9092 resolves only inside the Compose network, so direct execution needs a separately reachable broker. Redis stays a cache and is not used as a queue.
PASSWORD_HASH_CONCURRENCY sets the Argon2id memory budget in derivations of 64 MiB and four lanes each (from 1 to 4). Compose passes the value from .env, default 1, because the backend container has 1 CPU and 768 MB: a second derivation would only add 64 MiB while sharing the CPU. A directly launched backend without the variable uses the smaller of 2 and GOMAXPROCS. Further registrations and logins wait for memory until their request context ends. Compose also sets GOMEMLIMIT=600MiB, about 78% of the container limit, so the Go collector reclaims finished derivations before the container runs out of memory; change it together with the memory limit. The value is read and validated at startup; registration and login will use it once they are implemented. See ARCHITECTURE.md.
down stops containers and keeps named volumes. Do not delete database or file volumes during an ordinary stop.
Outbox relay
The backend runs the outbox relay in its own process next to the HTTP servers. The relay publishes committed outbox events to Kafka; its design is in ARCHITECTURE.md. Compose passes none of the settings below, so the stack uses the defaults; to change one, add it to the backend environment in deploy/docker/docker-compose.yml. A directly launched backend reads them from its environment. An invalid value stops startup.
| Variable | Default | Meaning |
|---|---|---|
RELAY_ENABLED |
true |
true or false. With false, or without DATABASE_URL, the relay does not run and events stay in the outbox. |
RELAY_BATCH_SIZE |
100 |
Events one pass locks and publishes, from 1 to 1000. |
RELAY_POLL_INTERVAL |
1s |
Wait after a pass that found no pending event, from 10ms to 5m. |
RELAY_PRODUCE_TIMEOUT |
10s |
Longest wait for the broker acknowledgements of one pass and for topic creation, from 1s to 2m. The pass keeps its transaction open for that long at most. |
RELAY_STATEMENT_TIMEOUT |
5s |
Server-side statement_timeout of each SQL statement of a pass, from 100ms to 1m. The pass transaction also gets idle_in_transaction_session_timeout of RELAY_PRODUCE_TIMEOUT plus this value, so PostgreSQL ends the transaction of a frozen or disconnected backend and releases its locks. |
RELAY_BACKOFF_INITIAL |
500ms |
Wait after the first failed pass; it doubles with each consecutive failure. |
RELAY_BACKOFF_MAX |
30s |
Longest wait between retries, from RELAY_BACKOFF_INITIAL to 10m. |
KAFKA_EVENTS_TOPIC |
lincodex.domain.events |
Topic for all domain events: up to 249 letters, digits, dots, underscores, or hyphens. |
KAFKA_EVENTS_TOPIC_PARTITIONS |
3 |
Partitions of a topic the relay creates, from 1 to 1000. |
KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR |
-1 |
Replication factor of a topic the relay creates: -1 takes the broker's default.replication.factor, otherwise from 1 to the broker count. |
KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS |
unset | min.insync.replicas of a topic the relay creates, at least 1 and not above an explicit replication factor. Unset leaves the broker default. |
KAFKA_PROVISION_TOPICS |
true |
With false the relay never creates the topic, and every publish fails until the topic exists. |
SHUTDOWN_TIMEOUT also bounds the relay: a pass in progress at shutdown has that long to finish, otherwise it rolls back and its events stay pending. Compose gives the backend stop_grace_period: 30s, which covers the whole shutdown budget described under Event consumers, so Docker does not kill the process while a pass commits; raise it together with SHUTDOWN_TIMEOUT.
The single-node stand creates the topic with the broker defaults of the Compose Kafka: replication factor 1 and min.insync.replicas 1. That is acceptable only for this stand: one broker cannot replicate, and losing its volume loses the events. A production cluster needs at least three brokers, a replication factor of at least 3, and min.insync.replicas 2, either as broker defaults or through KAFKA_EVENTS_TOPIC_REPLICATION_FACTOR=3 and KAFKA_EVENTS_TOPIC_MIN_INSYNC_REPLICAS=2. The producer always uses acks from all in-sync replicas, so with these values an acknowledged event survives the loss of one broker, and writes stop rather than land on a single replica when two of three brokers are down.
The relay creates a missing topic and never changes an existing one; when the existing topic has another partition count or replication factor than configured, the relay logs one warning. Adding partitions to the topic later moves aggregate keys to other partitions, so per-aggregate order is not guaranteed across that change.
When Kafka is unavailable, the backend still starts and serves the API. The relay logs warnings such as outbox relay could not prepare the event bus or outbox relay pass failed with the retry delay and keeps retrying; events stay in outbox_events until Kafka answers. In Compose the backend does not wait for the Kafka health check, so these warnings are expected during the first seconds after make -C deploy up. Relay logs carry the outbox_relay component and contain event IDs, counts, and broker errors, never payloads.
The internal /metrics endpoint shows the backlog: lincodex_outbox_relay_pending_events and lincodex_outbox_relay_oldest_pending_age_seconds are refreshed at most every 15 seconds, and lincodex_outbox_relay_events_total counts the published and failed outcomes. A growing age with a flat published count means the relay is stuck; the relay warnings name the event IDs, and ARCHITECTURE.md describes the causes. Every backend instance reports the same backlog, so aggregate it with max. Published rows stay in outbox_events; their retention is not implemented yet.
Event consumers
The backend runs one event consumer per registered handler in its own process next to the HTTP servers and the relay. A consumer reads KAFKA_EVENTS_TOPIC as a member of the group <CONSUMER_GROUP_PREFIX>.<consumer name>, applies each event once, and commits its offset only after the effect committed in PostgreSQL. The design is in ARCHITECTURE.md. Current state: one product handler is registered, notification_delivery (mail deliveries), so the backend runs one consumer in the group <CONSUMER_GROUP_PREFIX>.notification_delivery (lincodex.notification_delivery by default) when CONSUMER_ENABLED is true and DATABASE_URL is set. Compose passes none of them, so the stack uses the defaults; to change one, add it to the backend environment in deploy/docker/docker-compose.yml. An invalid value stops startup, also with consumers disabled.
| Variable | Default | Meaning |
|---|---|---|
CONSUMER_ENABLED |
true |
true or false. With false, or without DATABASE_URL, no consumer runs, and events wait in Kafka for as long as the topic retains them. |
CONSUMER_GROUP_PREFIX |
lincodex |
Prefix of every consumer group ID, up to 128 letters, digits, dots, underscores, or hyphens. Changing it starts new groups that read the topic from its earliest retained record; the dedup markers turn events that were already applied into duplicates. |
CONSUMER_MAX_ATTEMPTS |
5 |
Handler attempts for one event before it becomes a dead letter, from 1 to 20. Database failures outside the handler do not count. Must fit the rebalance budget below. |
CONSUMER_BACKOFF_INITIAL |
500ms |
Wait after the first failed attempt; it doubles with each consecutive failure. |
CONSUMER_BACKOFF_MAX |
10s |
Longest wait between attempts, from CONSUMER_BACKOFF_INITIAL to 5m. |
CONSUMER_HANDLER_TIMEOUT |
5s |
Bound of one attempt and of one dead letter write, from 100ms to 5m. It is also the server-side statement_timeout and idle_in_transaction_session_timeout of the consumer transaction. |
CONSUMER_MAX_POLL_RECORDS |
100 |
Records of one poll, from 1 to 10000. A consumer processes them while it holds group rebalancing, so a smaller value shortens that hold. |
CONSUMER_COMMIT_TIMEOUT |
5s |
Bound of one offset commit, from 100ms to 1m. |
CONSUMER_SHUTDOWN_GRACE |
5s |
Time the record in progress has to commit after shutdown begins; at most SHUTDOWN_TIMEOUT. After it the transaction rolls back, the offset stays uncommitted, and the next member processes the record. |
CONSUMER_REBALANCE_TIMEOUT |
60s |
Kafka rebalance timeout of every consumer group member, from 10s to 30m. Startup fails unless it exceeds the slowest record by 5 seconds. |
Rebalance budget. A consumer holds group rebalancing while it processes a poll, and a member that holds it longer than CONSUMER_REBALANCE_TIMEOUT is removed from the group, so its records are processed again by the next owner. The slowest record without a database outage takes CONSUMER_MAX_ATTEMPTS + 1 times CONSUMER_HANDLER_TIMEOUT (the attempts and the dead letter write), the longest backoff before each retry, and one CONSUMER_COMMIT_TIMEOUT. With the defaults that is 6 x 5s + (0.5 + 1 + 2 + 4)s + 5s = 42.5s, below 60s - 5s. A configuration that does not fit fails at startup with the computed value; lower the attempts or timeouts, or raise CONSUMER_REBALANCE_TIMEOUT, which also makes the group wait longer for a member that stopped responding. After every record that needed a retry or a dead letter the consumer commits at once, so only one slow record has to fit, not a whole poll.
Shutdown budget with the defaults:
- In parallel: the HTTP servers drain within
SHUTDOWN_TIMEOUT(10s); a relay pass gets the same 10s and up to 5s to roll back; every consumer getsCONSUMER_SHUTDOWN_GRACE(5s) for the record in progress, up to 5s to roll back a canceled transaction, andCONSUMER_COMMIT_TIMEOUT(5s) for its offsets. This phase ends after at most 15s. - Then all consumers leave their groups in parallel, each within
CONSUMER_COMMIT_TIMEOUTplus 2s (7s), and the clients and pools close in about 1s.
That is about 23s regardless of the number of consumers. Compose gives the backend stop_grace_period: 30s, so Docker does not kill the process while a transaction commits; raise it when you raise SHUTDOWN_TIMEOUT, CONSUMER_SHUTDOWN_GRACE, or CONSUMER_COMMIT_TIMEOUT.
A consumer needs one PostgreSQL connection; all consumers of a process share one pool sized to their count. Several backend instances share a group's partitions, so at most KAFKA_EVENTS_TOPIC_PARTITIONS instances process a consumer's events at once; the others stay idle members.
Operators watch two counters on the internal /metrics endpoint. lincodex_event_consumer_records_total{consumer,outcome} counts finished records: applied, duplicate (expected after a redelivery), ignored (another event type), and dead_lettered. Alert on any increase of dead_lettered; every series exists at zero from the consumer's start, so increase(...[15m]) > 0 fires on the first dead letter. lincodex_event_consumer_failures_total{consumer,stage} counts every failed operation, including the last handler attempt before a dead letter: a rising store count with flat applied means the consumer cannot reach PostgreSQL and its partition waits; a rising handler count means events keep failing; a rising poll count means the consumer cannot read Kafka (broker down, missing topic, or a group error); a rising commit count means offsets are not stored, so records will be delivered again after a restart or rebalance. Alert on poll or commit failures that continue for several minutes, for example increase(...{stage=~"poll|commit"}[5m]) > 0 held for 10 minutes. Consumer logs carry the event_consumer component, the group, topic, partition, offset, event ID, and event type, never the record value. A dead letter is logged at error level as event dead-lettered; the offset is committed and the record needs an operator with the class and reason.
Dead letters and replay
A dead letter is a record the consumer gave up on so that its partition can continue. error_class says why:
invalid_record: the value is not a valid event envelope. It did not come from the relay; find the producer that writes to the topic. It cannot be replayed as it is.handler_rejected: the handler reported that the event can never be applied, for example an unknownschema_version.handler_panic: the handler panicked; the log lineevent handler panickedwith the same event ID holds the stack.retries_exhausted: the handler failedCONSUMER_MAX_ATTEMPTStimes, for example because of a bug or a dependency it calls.
List them with psql in the database container (default app project):
docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \
exec postgres sh -c 'psql -U "$POSTGRES_USER" -d "$POSTGRES_DB"'
SELECT id, consumer_name, error_class, event_id, event_type, topic,
kafka_partition, kafka_offset, attempts, reason, dead_lettered_at
FROM consumer_dead_letters ORDER BY id;
The table holds no record value; value_size and value_sha256 identify the value. Replay a dead letter only after its cause is fixed, usually by deploying a corrected handler:
-
Replay one event from the outbox. For a dead letter with an
event_idand a class other thaninvalid_record, publish the event again:UPDATE outbox_events SET published_at = NULL WHERE event_id = '<event_id>';The relay publishes it again with the same
event_idat a new offset. Every consumer receives it: those that applied it find their marker and count aduplicate, and the consumer that failed applies it, because a dead letter writes no marker. This works as long as the outbox row exists (published rows are not deleted yet), also after Kafka dropped the original record. The event can arrive after later versions of its aggregate; handlers ignore versions they have already passed. -
Or rewind the group while Kafka still retains the record. Kafka resets offsets only for an empty group, so stop every member first (stop the backend instances or set
CONSUMER_ENABLED=false). A member that was killed instead of stopped stays in the group until its session timeout (45 seconds by default) ends; run the command below with--describeinstead of the reset options and wait until it lists no active member. Then:docker compose --env-file .env -p app -f deploy/docker/docker-compose.yml \ exec -e KAFKA_HEAP_OPTS=-Xmx128m kafka /opt/kafka/bin/kafka-consumer-groups.sh \ --bootstrap-server localhost:9092 --group lincodex.<consumer> \ --topic lincodex.domain.events:<partition> --reset-offsets --to-offset <offset> --executeThe group then reads that partition again from the offset. Records it already applied are duplicates; other dead letters in the range are attempted again, and one that fails again updates its row with the new class, reason, and attempt count instead of adding another.
--describealso shows the group's offsets and lag. -
Check the result and close the dead letter: the event is applied when
SELECT 1 FROM consumer_processed_events WHERE consumer_name = '<consumer>' AND event_id = '<event_id>'returns a row. Then delete the row withDELETE FROM consumer_dead_letters WHERE id = <id>, or keep it as a record of the incident.
To inspect an invalid_record while the topic retains it, read exactly that record with kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic <topic> --partition <partition> --offset <offset> --max-messages 1 and compare its SHA-256 with value_sha256. The value can contain personal data, so do not paste it into tickets or chats.
Scheduled jobs
The backend runs the scheduled job worker as a goroutine of the backend process next to the HTTP servers, the relay, and the consumers. It runs jobs that usecases scheduled in their transactions once they fall due; the design is in ARCHITECTURE.md. Current state: no product job kind is registered, so the backend logs no scheduled job kind is registered at startup and runs no worker; the settings below are still validated. With a registered kind, the worker runs when JOBS_ENABLED is true and DATABASE_URL is set. Compose passes none of the settings, so the stack uses the defaults; to change one, add it to the backend environment in deploy/docker/docker-compose.yml. A directly launched backend reads them from its environment. An invalid value stops startup, also with the worker disabled.
| Variable | Default | Meaning |
|---|---|---|
JOBS_ENABLED |
true |
true or false. With false, or without DATABASE_URL, no job runs; due jobs wait in scheduled_jobs and run after the worker starts again, with their original due_at. |
JOBS_POLL_INTERVAL |
1s |
Wait after a pass that claimed less than a full batch, from 10ms to 5m. It is also the usual delay of a job after its due time. |
JOBS_BATCH_SIZE |
10 |
Jobs one claim leases, from 1 to 100. They run one after another under leases taken together, so a batch should finish well within one lease. |
JOBS_LEASE_DURATION |
1m |
How long a claimed job belongs to one worker, from 1s to 1h. It bounds one handler attempt and is the server-side statement_timeout and idle_in_transaction_session_timeout of the job transaction. A worker that crashed delays its jobs by at most this long. |
JOBS_MAX_ATTEMPTS |
5 |
Attempts of a job scheduled without its own limit before it is dead, from 1 to 100. Database failures outside the handler and shutdown do not count. |
JOBS_BACKOFF_INITIAL |
1s |
Delay before the first retry of a failed job; it doubles with each failed attempt. The same backoff spaces claims while the database fails. |
JOBS_BACKOFF_MAX |
5m |
Longest delay before a retry, from JOBS_BACKOFF_INITIAL to 24h. |
JOBS_SHUTDOWN_GRACE |
5s |
Time the job in progress has to commit after shutdown begins; at most SHUTDOWN_TIMEOUT. After it the transaction rolls back and the job is released unfinished. |
Due times and leases are compared with the backend clock, not the database clock, so keep the hosts of all backend instances synchronized with NTP. A clock ahead runs jobs early and takes over leases early; the row lock still prevents a second run while a handler is in progress.
Shutdown budget. The worker stops in parallel with the other workers: JOBS_SHUTDOWN_GRACE (5s) for the job in progress, up to 5s to roll back a canceled transaction, and up to 5s to release the unfinished jobs, 15s at most. This fits the first phase of the budget under Event consumers, so the total stays about 23s within stop_grace_period: 30s; raise that together with JOBS_SHUTDOWN_GRACE. If the backend is killed instead, its jobs stay running until their leases expire and then run on another instance or after the restart.
The worker uses its own PostgreSQL pool of at most two connections. Several backend instances share the jobs: each claim skips rows that another instance locks, and every instance can run every registered kind.
Operators watch lincodex_scheduled_jobs_total{kind,outcome} on the internal /metrics endpoint: done, retry (an attempt failed and the job waits for its backoff), dead, lease_lost (the job was canceled or reclaimed while this instance held it), and released (given back unfinished at shutdown or after a database failure). Every series exists at zero from the start, so alert on increase(lincodex_scheduled_jobs_total{outcome="dead"}[15m]) > 0. lincodex_scheduled_jobs_due and lincodex_scheduled_jobs_oldest_due_age_seconds describe due jobs that wait for a worker; an age that keeps growing beyond a few poll intervals means no instance claims them, for example because the worker is disabled, the database fails, or no running instance has the handler of their kind. lincodex_scheduled_jobs_dead counts dead jobs. Every instance reports the same database-wide gauges, so aggregate them with max. During a rolling deployment that adds a new kind, its jobs that already fell due wait until an instance with the handler runs, and the age can briefly look like a stuck worker; hold an age alert for longer than a deployment takes. Logs carry the scheduled_jobs component, the lease owner, job ID, kind, attempt, and error class, never the key or payload; a dead job is logged at error level as scheduled job is dead; it needs an operator.
Dead jobs
last_error_class says why a job is dead: handler_rejected (the handler can never run it), handler_panic (the log line scheduled job handler panicked with the same job ID holds the stack), lease_expired (its last started attempt stopped without finishing, usually a crash or a kill, or its failure could not be recorded because the database failed at that moment), or the class of the last failed attempt after the attempts ran out: handler_failed, timeout, conflict, or effect_rejected. completion_conflict means the handler changed its own job other than by canceling it. List dead jobs and jobs that are overdue with psql in the database container (see Dead letters and replay for the command that opens it):
SELECT id, kind, dedup_key, attempts, max_attempts, last_error_class,
due_at, available_at, updated_at
FROM scheduled_jobs WHERE status = 'dead' ORDER BY updated_at;
SELECT kind, status, count(*), min(available_at)
FROM scheduled_jobs
WHERE status IN ('pending', 'failed', 'running') AND available_at <= now()
GROUP BY kind, status;
The key identifies a product record, such as an invitation ID; the payload holds identifiers only. After the cause is fixed, usually by deploying a corrected handler, run a dead job again. Change only available_at, never due_at: the handler decides by the deadline in due_at.
UPDATE scheduled_jobs
SET status = 'failed', attempts = 0, available_at = now(), updated_at = clock_timestamp()
WHERE id = <id> AND status = 'dead';
A worker claims it within one poll interval and runs it with fresh attempts. To give a dead job up, set status = 'cancelled' with the same guard; its key stays reserved, so the product flow cannot schedule it again. Do not delete rows: a deleted key can be scheduled again and run a second time.
The backend sends mail through the MailSender port. EMAIL_PROVIDER selects exactly one transport: resend (the Resend HTTP API, the primary provider for the working stand), smtp (a separate SMTP relay), or disabled. It has no default, and there is no fallback: when the selected transport cannot start, the backend stops instead of switching to another one. Settings of transports that are not selected are not read.
Current state: this build contains the disabled and resend transports. With smtp, the backend validates the SMTP settings and then exits with EMAIL_PROVIDER=smtp: mail transport is not available in this build; under Compose, restart: unless-stopped restarts the container repeatedly. SMTP is outside the MVP. .env.example and make -C deploy smoke use disabled, so local runs need no key; the working stand sets EMAIL_PROVIDER=resend and RESEND_API_KEY explicitly. No flow sends mail yet: mail requests are stored as deliveries (see Mail deliveries), and the worker that calls the transport is planned.
resend sends each message with one request to https://api.resend.com/emails. Building the transport makes no network call, so startup checks neither the key nor the sender domain; a wrong key or an unverified domain in EMAIL_FROM shows up as a rejected send. One attempt is limited by EMAIL_TIMEOUT. The transport follows no redirects, never retries, and logs nothing; retries, backoff, rate-limit pacing, and outcome records belong to the planned delivery layer, and the wait for a daily or monthly quota reset is decided by the quota gate (see Mail quotas). Each request carries the message's idempotency key, and Resend deduplicates the same key and body for 24 hours; after that window a retry may send the mail twice. A success means that Resend accepted the request and returned a message ID, not that the mail was delivered or read. A timeout, a lost answer after the request was sent, or a Resend 500 error is unknown (delivery_uncertain), not a failure. The backend process follows the standard HTTPS_PROXY and NO_PROXY variables, but the Compose backend service does not pass them, so under Compose the request goes directly to Resend; a stand that needs an egress proxy must add them to the backend environment. The full mapping of answers is in ARCHITECTURE.md.
disabled sends nothing. Every send returns ErrMailChannelUnavailable without a provider message ID and is never reported as accepted or delivered. It does not confirm an email address, mark an account verified, or skip an account check. The startup log contains mail transport selected with email_provider and, for disabled, a mail delivery is disabled warning.
| Variable | Default | Validation |
|---|---|---|
EMAIL_PROVIDER |
none, required | resend, smtp, or disabled, case-insensitive |
EMAIL_FROM |
none, required | One mailbox: no-reply@example.com or Lincodex <no-reply@example.com>. Printable ASCII only. The address follows the account address rules: unquoted local part and a DNS domain with at least two labels, no IP literal. |
EMAIL_ACCOUNT |
default |
Label of the provider account that new deliveries are pinned to and that the quota is counted under: 1 to 64 lowercase letters, digits, ., _, or -, starting with a letter or digit. Never the key. Change it only with a real account change; renaming it resets the local quota count. |
EMAIL_TIMEOUT |
10s |
Go duration from 1s to 1m; limits one transport attempt |
EMAIL_QUOTA_DAILY |
100 for resend and disabled; none for smtp, where it is required |
Recipients per UTC day through the configured provider account: an integer from 1 to 1000000000. Empty counts as unset. No value turns the quota off. |
EMAIL_QUOTA_MONTHLY |
3000 for resend and disabled; none for smtp, where it is required |
Recipients per UTC calendar month: an integer from 1 to 1000000000, not below EMAIL_QUOTA_DAILY. Empty counts as unset. |
APP_PUBLIC_URL |
none, required | Public origin for links in mail: https://host[:port], or http only for localhost, 127.0.0.1, or [::1]. No credentials, path, query, or fragment; one trailing / is dropped. |
RESEND_API_KEY |
empty | Read only for resend, where it is required. Printable ASCII without whitespace. The re_ prefix shown in Resend examples is not enforced. |
SMTP_HOST |
empty | Read only for smtp, where it is required. Hostname or IP address without a port. |
SMTP_PORT |
empty | Required for smtp. Integer from 1 to 65535. |
SMTP_USERNAME, SMTP_PASSWORD |
empty | Required for smtp; an anonymous relay is not supported. |
SMTP_TLS_MODE |
empty | Required for smtp. starttls (upgrade with STARTTLS, usually port 587) or tls (TLS from the start, usually port 465). Plaintext SMTP is not supported. |
Compose passes these variables from the root .env; it passes an unset EMAIL_QUOTA_DAILY or EMAIL_QUOTA_MONTHLY as an empty value, which the backend reads as unset. EMAIL_PROVIDER, EMAIL_FROM, and APP_PUBLIC_URL are required, so Compose refuses to render the project without them; copy the mail block from .env.example into an existing .env. Keep RESEND_API_KEY and SMTP_PASSWORD in the server environment or a deployment secret store and never commit them. Configuration errors name the setting but never print its value, and the startup log names only the selected provider.
Mail deliveries
A notification request is a row in mail_requests until the consumer notification_delivery turns it into a row in deliveries and deletes it; the model is in ARCHITECTURE.md. Migration 00006 creates mail_requests, deliveries, and delivery_attempts at startup; it needs no setting. The deliveries are only stored for now: the worker that sends them is planned, so no row leaves pending. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line.
- Each delivery is pinned to
EMAIL_PROVIDERandEMAIL_ACCOUNTat creation, and a later configuration change applies only to new deliveries. ChangeEMAIL_ACCOUNTtogether withRESEND_API_KEYwhenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Deliveries created whileEMAIL_PROVIDER=disabledstay pinned todisableduntil the sending worker (TASK-016) moves them withRebind, which is allowed only before the first attempt. - The rows hold the recipient address and the rendered bodies, and a waiting
mail_requestsrow holds the raw notification text; verification and password reset bodies hold a live one-time token until it is used or expires. Treat read access todeliverieslike access to those links, and keep database dumps and backups under the same protection. Retention of finished deliveries is not implemented yet. - To inspect deliveries, select metadata only, for example
SELECT id, kind, template_version, status, attempt_count, next_attempt_at, last_attempt_at, provider, provider_account, created_at FROM deliveries ORDER BY created_at DESC LIMIT 50, andSELECT attempt_number, attempted_at, outcome, rejection, provider_code, status_after FROM delivery_attempts WHERE delivery_id = '<id>' ORDER BY attempt_number.SELECT count(*), min(created_at) FROM mail_requestsshows requests the consumer has not handled yet; a growing count means the consumer is stopped or its events are dead-lettered. Do not selectrecipient_email,subject,text_body,html_body, or themail_requeststext columns, and never paste them into tickets or chats. - Do not edit a stored delivery by hand: a trigger refuses any change to the recipient, content, or idempotency key and a change of the provider account after the first attempt, and the attempt history refuses updates. A delivery in
waiting_quotawaits for the quota reset atnext_attempt_at; see Mail quotas. Withoutnext_attempt_atits reset is unknown and it needs an operator decision. - Logs name a delivery only by
delivery_id(with the event ID), never by address or subject. Skipped requests are logged at info level:mail request skipped because it was already handled or its account was deletedandnotification skipped because the recipient address is not verified. A request that breaks the event contract is ahandler_rejecteddead letter of the consumernotification_delivery; see Dead letters and replay. Replaying it is safe: the delivery ID keeps one delivery per request.
Mail quotas
Migration 00007 creates mail_quota_usage and the reservation journal mail_quota_reservations at startup; it needs no setting. The quota gate is implemented, but the sending worker that calls it is planned (TASK-016), so the current build counts nothing yet. The model is in ARCHITECTURE.md.
- Set
EMAIL_QUOTA_DAILYandEMAIL_QUOTA_MONTHLYto the plan of the provider account named byEMAIL_ACCOUNT. The defaults are Resend Free: 100 recipients per UTC day and 3000 per month, as checked on 2026-10-05. Check the account's current quota in the Resend dashboard before the stand goes live and after any plan change. Withsmtp, set both to the relay's limits; startup fails without them. A changed value applies after a restart. - Change
EMAIL_ACCOUNTonly together with a real change of the provider account, that is, a key of another account. The local count is kept per account label, so renaming the label for the same account starts a new count from zero while the provider keeps the old one. At startup the backend logsmail quota usagewith the provider, account, and the current day and month usage and limits, and warns when other labels of the same provider have usage this month. - When a quota is used up, deliveries wait in
waiting_quotauntilnext_attempt_at: the next 00:00 UTC for the day, the first day of the next month at 00:00 UTC for the month. Nothing buys a plan, switches the account to a paid tier, or moves mail to another transport or account. The account itself can see that its mail waits and until when through the status reader described in ARCHITECTURE.md; no HTTP route shows it yet. - To see the state, select only counters and metadata, for example
SELECT provider, provider_account, period_kind, period_start, used_recipients, provider_exhausted_at FROM mail_quota_usage ORDER BY period_start DESC, period_kind LIMIT 10,SELECT count(*), min(next_attempt_at) FROM deliveries WHERE status = 'waiting_quota', and, for sends that were counted but never settled,SELECT count(*), min(reserved_at) FROM mail_quota_reservations WHERE settled_outcome IS NULL AND released_at IS NULL. Logs showmail quota is used up; the delivery waits for the resetand, when the provider itself refused,the mail provider reported its quota used up; local sending stops until the reset. - Choices while mail waits: wait for the reset, which needs no action; or, after a deliberate plan change with the provider, raise the limits and restart the backend, so new sends are admitted again while parked deliveries keep their stored
next_attempt_at; or deliberately switch the transport or account (see Mail deliveries for what stays pinned). Do not lowerused_recipientsor edit the journal by hand to free sends: the provider keeps its own count, so the sends would only be refused. provider_exhausted_aton a row means that the provider refused with a quota answer while the local count still had room. Possible reasons: the account also sends from elsewhere; Resend counts received (inbound) mail against the same quota; or the configured limit is above the plan. Align the limits with the plan.- Resend's monthly quota follows the account's billing cycle, while the gate's month is the UTC calendar month. After a monthly refusal the delivery retries at the next UTC month start; if the billing cycle resets later, that retry is refused again and waits another month. A manual retry with an audit record is planned with the retry policy (TASK-017).
- Lowering a limit takes effect on the next reservation. During a rolling deploy, instances with the old and the new limits run side by side and each checks the limit it was started with, so a lowered limit holds only once every instance runs the new configuration. Switching
EMAIL_PROVIDERtosmtpstarts separate counters for the relay under its own stated limits; deliveries pinned to the old account are refused by the gate rather than sent without a limit.
Mail templates
Implemented: the renderer in backend/internal/usecase/notification/mailtemplate/ with templates for email verification, password reset, and a short notification. The delivery consumer renders notifications with it when it stores a delivery; registration, verification, password reset, and sending are planned, so the current build sends no message.
- Templates are embedded in the binary with
go:embedand parsed once when the renderer is created; a broken template fails its creation. Each version has three files:<kind>.v<N>.subject.tmpl,<kind>.v<N>.txt.tmpl, and<kind>.v<N>.html.tmpl. The HTML part useshtml/template, the plain-text part and the subject usetext/template. Every transport sends the same rendering; templates hold no provider settings, keys, or sender address. - Links start with
APP_PUBLIC_URL, which the renderer checks again with the same rules. Verification:<APP_PUBLIC_URL>/verify-email#token=<token>; password reset:<APP_PUBLIC_URL>/reset-password#token=<token>(the page and the API for the reset are planned). The token is only in the URL fragment, never in the query. A notification link is a path inside the application, such as/candidate/invitations; an absolute URL,//host, a scheme such asjavascript:, a query, a fragment, a percent sign, and.or..segments are rejected. - Messages contain no name, email address, or other contact. Caller text in a notification is escaped in the HTML part; control and bidirectional characters are removed from the plain-text part, and the subject becomes one line, so CR and LF cannot add header lines. The notification subject is limited to 100 characters and the body to 2000.
- Copy is in Russian. A released version is immutable: changing copy adds the next version, for example
verification.v2, and switches the current version in code. Versions share no files, so one version cannot change the body of another. Each rendering carries its version and a SHA-256 content hash over the version, subject, and both parts; the same version and data always give the same body. A delivery stores the rendered body with the hash, and a retry sends the stored body instead of rendering again, so a new version applies to new deliveries only and an old version's files are not needed to send a stored delivery. - The renderer does not log. A rendering and notification data print only the kind, version, and content hash in
fmtandslogoutput; tokens, links, and bodies are never printed. - Golden files in
testdata/make every copy change visible in review. After an intended change, rungo test ./internal/usecase/notification/mailtemplate -updatefrombackend/and review the diff.
Separate ML Compose project
ML uses a separate Compose file and project; it does not require or start Redis or SeaweedFS in the current scaffold. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty.
The ML image uses python:alpine and upgrades system packages during the build. Dependencies are installed with uv only in the build stage; the final runtime contains the prepared virtual environment without pip or ensurepip. Current dependencies support musl. Check Alpine compatibility before adding inference or GPU libraries; glibc-dependent libraries will require a different validated runtime.
make -C deploy ml-config
make -C deploy ml-up
make -C deploy ml-logs
make -C deploy ml-down
GET /healthz checks the process. GET /readyz checks inference readiness and returns 503 while a model is unavailable. The current scaffold has no working model. Readiness does not measure model quality or inference behavior.
Separate monitoring Compose project
Start the core project first. Monitoring joins its Docker network. Monitoring starts separately and is not required to run the app:
make -C deploy monitoring-config
make -C deploy monitoring-up
make -C deploy monitoring-logs
make -C deploy monitoring-down
Grafana is available at http://127.0.0.1:3000. Credentials come from GRAFANA_ADMIN_USER and GRAFANA_ADMIN_PASSWORD in .env. Prometheus, Loki, exporters, and backend metrics publish no host ports.
Prometheus retains metrics for 14 days with a 4 GB size limit. Loki retains logs for 7 days. Alloy discovery filters by Compose project and collects logs only from backend, frontend, postgres, redis, and seaweedfs. Kafka logs and metrics are not collected yet; read the logs with make -C deploy logs. Loki labels are limited to service and environment; do not add user IDs, addresses, resume text, request bodies, or full URLs.
Frontend telemetry is not connected in the React app yet. Nginx and Alloy provide a restricted /telemetry receiver and Faro configuration, but the UI SDK and end-to-end event check are absent.
Alloy uses docker-socket-proxy for container discovery. The proxy enables only the needed Docker API sections for containers, events, ping, and version; POST is disabled. Set the socket path with DOCKER_SOCKET_PATH. Rootless Docker may use a path such as /run/user//docker.sock; use the path on your own host instead of copying another developer's local path. The proxy restricts API sections, but access to the Docker socket remains privileged and its exact configuration needs review.
PostgreSQL creates a separate exporter role only while initializing an empty volume and when POSTGRES_EXPORTER_USER and POSTGRES_EXPORTER_PASSWORD are set. Set both before the first make -C deploy up. Changing them after the volume exists does not rerun the init script.
For remote ML scraping, set ML_METRICS_TARGET to hostname:port or IPv4:port and verify private routing and firewall rules. The standalone ML host does not yet have a separate Alloy config for forwarding its container logs to Loki.
Edge proxy, HTTPS and tunnel
The Compose stack serves plain HTTP on the host. A public site puts a separate edge host in front of it: the edge terminates TLS and forwards every request through a dedicated tunnel to the app host. The files are in deploy/edge/; this section is the runbook. It describes the configuration in the repository. A rollout is an external action, and the test steps below show what a rollout has to prove.
browser --HTTPS--> edge nginx (EDGE_LISTEN_IP:80,443)
--AmneziaWG tunnel (10.79.0.0/30)--> app host (10.79.0.2:8080)
= frontend container (Nginx) --> backend
| Role | What runs there | Address in the reference rollout |
|---|---|---|
| Edge host | nginx, certbot, the AmneziaWG server end | public 213.165.42.19 and 89.185.85.208; tunnel 10.79.0.1 |
| App host | Docker Compose core stack, the AmneziaWG client end | LAN 192.168.10.111 behind NAT; tunnel 10.79.0.2 |
The edge host is shared with other services. Everything here only adds: nginx binds the one address in EDGE_LISTEN_IP and never a wildcard, the tunnel uses its own interface and subnet, and no existing interface, listener, container, or firewall rule is changed.
Configuration
All names and addresses come from deploy/edge/edge.env (copy deploy/edge/edge.env.example; the file holds no secrets and Git ignores it). The main values are EDGE_DOMAIN, EDGE_CERT_NAME, EDGE_LISTEN_IP, EDGE_ACME_WEBROOT, EDGE_HSTS_MAX_AGE, EDGE_MAX_BODY, and the tunnel values AWG_IFACE, AWG_EDGE_IP, AWG_APP_IP, AWG_PREFIX, AWG_EDGE_ENDPOINT_IP, AWG_PORT, AWG_MTU, and AWG_KEEPALIVE. The edge proxies to AWG_APP_IP:APP_HTTP_PORT. The tunnel subnet must not overlap any route or Docker range on either host; ip route on both hosts is the check.
make -C deploy edge-config # render the templates and run nginx -t in a container
make -C deploy edge-render # write deploy/edge/rendered/nginx
edge-config renders the nginx templates and both tunnel templates (with throwaway keys), fails when a placeholder has no value or a listen directive is not bound to EDGE_LISTEN_IP, and runs nginx -t in nginx:stable-alpine (EDGE_NGINX_IMAGE changes it) with a self-signed certificate at the path the configuration expects. It needs Docker and proves syntax only, not that a certificate exists or the host is reachable. The Ubuntu edge package is nginx 1.28; keep the image close to it.
deploy/edge/scripts/render.sh validates every value before it substitutes it. Keys and obfuscation parameters are not part of edge.env: deploy/edge/scripts/awg-keys.sh writes them to a root-only parameters file on each host (/etc/amnezia/amneziawg/awg-lincodex.params), and render.sh --params reads that file to produce the tunnel configuration.
One origin and the Secure cookie
The browser sees only https://<EDGE_DOMAIN>. The SPA and /api come from the same origin: the edge forwards every path unchanged, and the frontend container serves the SPA with its try_files ... /index.html fallback, so a deep link such as /some/deep/link returns the SPA, and proxies /api/ to Go. The planned session cookie is __Host-lincodex_session with Secure, HttpOnly, and SameSite=Strict. Browsers accept it only from an HTTPS page, with Path=/ and no Domain, which the single HTTPS origin gives. The edge keeps Host as the public name and sets X-Forwarded-Proto: https; the frontend container's Nginx keeps that value for the backend ($forwarded_proto in deploy/nginx/conf.d/app.conf) and otherwise reports its own scheme. APP_PUBLIC_URL in the app host .env must be https://<EDGE_DOMAIN>, which is the only origin value the backend reads.
Registration and login are not implemented yet (the operations answer 501), and the backend does not read X-Forwarded-Proto. Sign-in through the edge is therefore not verified end to end; what is verified is the transport the cookie needs (HTTPS, one origin, the original host and scheme forwarded).
Request handling at the edge
- Port 80 serves only
/.well-known/acme-challenge/fromEDGE_ACME_WEBROOTand answers everything else with a 301 tohttps://<EDGE_DOMAIN>plus the original path and query. The target is the configured name, not the requestHost. A request for any other name is dropped (nginx 444) on port 80 and refused at the TLS handshake on port 443. - Port 443 allows TLS 1.2 and 1.3 with the Mozilla intermediate cipher list, HTTP/2, no session tickets, and
Strict-Transport-Security: max-age=<EDGE_HSTS_MAX_AGE>; includeSubDomainswithoutpreload. The default max-age is 180 days; raise it to a year and consider preload only after the site has stayed on HTTPS. The upstream security headers (X-Content-Type-Options,Referrer-Policy,X-Frame-Options,Permissions-Policy) pass through from the frontend container. - OCSP stapling is off on purpose: Let's Encrypt certificates no longer carry an OCSP responder URL, so there is nothing to staple. HTTP/3 is off because it would need UDP 443, which another service on the edge host owns.
- Compression is off for
/api/and limited to CSS, JavaScript, SVG, and the HTML shell elsewhere (no JSON). Compressing responses that mix secrets with attacker-influenced content enables BREACH; a CSRF token delivered in an API response must never be compressed. Revisit this if a secret is ever rendered into HTML. X-Forwarded-ForandX-Real-IPare replaced with the connecting address, not appended to client values, because the edge is the first trusted hop. The frontend container then appends the tunnel peer, so the backend reads the client address as the firstX-Forwarded-Forentry. The container's ownX-Real-IPand the/telemetryrate limit see the tunnel peer or the Docker gateway address, so all clients share that bucket until the container trusts the edge for real client addresses.client_max_body_sizeisEDGE_MAX_BODY(10 MB, equal to the container limit). The 5 MB resume limit is a per-feature policy checked by the backend. Timeouts: 5 s to connect, 60 s to send and read (the container gives Go 30 s), 60 s for a request body.- The access log (
/var/log/nginx/lincodex.access.log, rotated by the package logrotate rule) records the path without the query string, so values such as addresses in a query do not reach the log.
Rollout on the edge host
Ubuntu packages only; no system upgrade. Install nginx and certbot without starting nginx on its default wildcard site:
printf '#!/bin/sh\nexit 101\n' | sudo tee /usr/sbin/policy-rc.d >/dev/null && sudo chmod 755 /usr/sbin/policy-rc.d
sudo apt-get install -y --no-install-recommends nginx certbot
sudo rm -f /usr/sbin/policy-rc.d /etc/nginx/sites-enabled/default
-
Check that the domain resolves to
EDGE_LISTEN_IP(dig +short <domain> @1.1.1.1) and that nothing listens on TCP 80 and 443 (ss -tlnp). -
Copy
deploy/edgeto the host, createedge.env, and render:deploy/edge/scripts/render.sh --env deploy/edge/edge.env --out deploy/edge/rendered nginx. -
Install the ACME directory and the first two files, then the firewall rules (ufw only gains rules; keep a second SSH session open while changing it):
sudo install -d -m 755 /var/www/certbot sudo install -m 644 deploy/edge/rendered/nginx/00-default.conf deploy/edge/rendered/nginx/lincodex-http.conf /etc/nginx/conf.d/ sudo nginx -t sudo ufw allow in to <EDGE_LISTEN_IP> port 80 proto tcp comment 'lincodex ACME and redirect' sudo ufw allow in to <EDGE_LISTEN_IP> port 443 proto tcp comment 'lincodex HTTPS' sudo systemctl enable --now nginx -
Install the renewal hook and issue the certificate. Run the staging dry run first; the production CA limits repeated failures. The account has no email address (
--register-unsafely-without-email), so Let's Encrypt cannot send expiry notices; add an address later withcertbot update_account --email <address>.--agree-tosaccepts the Let's Encrypt subscriber agreement.sudo install -d -m 755 /etc/letsencrypt/renewal-hooks/deploy sudo install -m 755 deploy/edge/certbot/reload-nginx.sh /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh sudo certbot certonly --webroot -w /var/www/certbot -d <domain> --cert-name <domain> \ --register-unsafely-without-email --agree-tos --non-interactive --dry-run sudo certbot certonly --webroot -w /var/www/certbot -d <domain> --cert-name <domain> \ --register-unsafely-without-email --agree-tos --non-interactive -
Install the HTTPS file and reload:
sudo install -m 644 deploy/edge/rendered/nginx/lincodex-https.conf /etc/nginx/conf.d/ && sudo nginx -t && sudo systemctl reload nginx. The site answers 502 or 504 until the tunnel and the app host are up. -
Install the tunnel end (below), then
sudo ufw allow in to <AWG_EDGE_ENDPOINT_IP> port <AWG_PORT> proto udp comment 'lincodex tunnel'.
Tunnel
AmneziaWG runs in userspace (amneziawg-go) so that nothing depends on a kernel module for the host kernel. Both hosts use the same two pieces:
amneziawg-tools(awg,awg-quick, and theawg-quick@.serviceunit) from the Amnezia PPA package for the release, downloaded and checked against the SHA-256 in the PPA package index, then installed withdpkg -i. The PPA is not added to apt, so the package does not update itself.amneziawg-go, built from the upstream tagv3.1.20260828(commitb5928efb6ca1) withCGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -trimpath -ldflags "-s -w"and installed as/usr/local/bin/amneziawg-go. The reference build has SHA-2565e8877b58afdc4667be196aebb994839d167a4f189c5507e0155cc72ea1b14fa. It is built off the hosts so they need no Go toolchain.
Keys and parameters are generated on the hosts and never leave them except as public data:
# edge, as root
deploy/edge/scripts/awg-keys.sh init /etc/amnezia/amneziawg/awg-lincodex.params
deploy/edge/scripts/awg-keys.sh export /etc/amnezia/amneziawg/awg-lincodex.params > shared.env
# app host, as root, after shared.env is copied over SSH
deploy/edge/scripts/awg-keys.sh init /etc/amnezia/amneziawg/awg-lincodex.params --shared shared.env
deploy/edge/scripts/awg-keys.sh export /etc/amnezia/amneziawg/awg-lincodex.params > app-shared.env
# edge, after app-shared.env is copied back
deploy/edge/scripts/awg-keys.sh peer /etc/amnezia/amneziawg/awg-lincodex.params app-shared.env
The exchanged files contain a public key and the obfuscation parameters. The parameters are shared secrets of the tunnel; delete the copies after use. Then, on each host (awg-edge on the edge, awg-app on the app host):
deploy/edge/scripts/render.sh --env deploy/edge/edge.env --out /tmp/awg --params /etc/amnezia/amneziawg/awg-lincodex.params awg-edge
sudo install -m 600 /tmp/awg/awg/awg-lincodex.conf /etc/amnezia/amneziawg/awg-lincodex.conf && rm -r /tmp/awg
sudo install -D -m 644 deploy/edge/systemd/awg-quick-userspace.conf /etc/systemd/system/awg-quick@awg-lincodex.service.d/userspace.conf
sudo systemctl daemon-reload && sudo systemctl enable --now awg-quick@awg-lincodex
The app host initiates the handshake from behind NAT and sends a keepalive every AWG_KEEPALIVE seconds; the edge has no peer endpoint. AllowedIPs lists only the other end's tunnel address, so the tunnel installs no default route and carries nothing else. Check it with sudo awg show (a recent latest handshake) and ping <peer tunnel IP>. The units start at boot. The userspace daemon is one process per interface; systemd does not restart it by itself, so check the handshake after an incident (systemctl restart awg-quick@awg-lincodex rebuilds the interface).
Rollout on the app host
-
Install Docker Engine and the Compose plugin from the official Docker apt repository (
docker-ce,docker-compose-plugin). The tunnel setup above comes first, because the next steps use its address. -
Make Docker wait for the tunnel:
sudo install -D -m 644 deploy/edge/systemd/docker-after-awg.conf /etc/systemd/system/docker.service.d/10-lincodex-awg.conf && sudo systemctl daemon-reload. Docker cannot publish a port on an address that does not exist yet, and containers with a restart policy start with the daemon, so the tunnel interface has to exist first. -
Copy the committed tree of the repository to the host (
git archive HEAD), copy.env.exampleto.envwith mode 600, and generate the secrets on the host (passwords, S3 keys, and aKAFKA_CLUSTER_IDas described in.env.example). Set these values:APP_HTTP_BIND=10.79.0.2 APP_PUBLIC_URL=https://<EDGE_DOMAIN> EMAIL_PROVIDER=disabledAPP_HTTP_BINDis the address the frontend port is published on; the default127.0.0.1keeps a local stack private.EMAIL_PROVIDER=disabledsends no mail. To enable mail later, setEMAIL_PROVIDER=resend,RESEND_API_KEY, andEMAIL_FROMin the server.envand runmake -C deploy upagain; the key stays only in that file. -
Start the stack with
make -C deploy upand checkcurl -s http://10.79.0.2:8080/healthzon the app host.
Firewall
On the edge host, ufw gains three rules: 80/tcp and 443/tcp to EDGE_LISTEN_IP, and the tunnel port over UDP to AWG_EDGE_ENDPOINT_IP. The host's other rules, WireGuard interface, and UDP 443 listener are untouched.
On the app host, ufw denies incoming traffic by default and rate-limits SSH. The rollout keeps SSH open to any source with ufw limit: the app host has only a private address behind NAT, and the operator's SSH source changes with the VPN path (both a LAN address and a VPN address were observed), so a source filter would lock the operator out. Narrow it to fixed sources only when they are known. The tunnel port needs no inbound rule because the app host initiates and replies are tracked connections. Arm a dead-man switch that disables ufw after five minutes, enable ufw, open a second SSH session, and only then stop the timer:
sudo systemd-run --unit=ufw-deadman --on-active=300 /usr/sbin/ufw --force disable
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw limit 22/tcp comment "SSH"
sudo ufw allow in on awg-lincodex from 10.79.0.1 to 10.79.0.2 port 8080 proto tcp comment "lincodex edge to app"
sudo ufw --force enable
# From a new terminal: ssh <app-host> true, then:
sudo systemctl stop ufw-deadman.timer
Docker bypasses ufw for published ports: it adds its own NAT and FORWARD rules, so a ufw rule does not stop traffic to a published container port, and the last rule above does not govern it. The control that holds is the publish address. With APP_HTTP_BIND=10.79.0.2, the port answers only for packets addressed to the tunnel address, not on the LAN address or on loopback. A host on the same LAN can still send a packet addressed to 10.79.0.2 to the app host's MAC address if it adds a route for that address, so the port is protected from the network only by the tunnel being private and the LAN being trusted. Never publish the frontend port on 0.0.0.0. Keep every other Compose port unpublished, as the stack already does.
Renewal and reload
Ubuntu's certbot.timer runs certbot renew twice a day and renews a certificate that expires within 30 days. The renewal uses the webroot of the first issuance, so port 80 must keep serving /.well-known/acme-challenge/. After a renewal, the deploy hook /etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh runs nginx -t && systemctl reload nginx; it does not run when nothing was renewed. Check the pieces:
sudo certbot renew --dry-run --no-random-sleep-on-renew
systemctl list-timers certbot.timer
sudo certbot certificates
A reload starts new workers with the new certificate and configuration and lets the old workers finish their open connections, so in-flight requests and keep-alive connections are not dropped. Sessions are not held by nginx at all: the planned design keeps them in PostgreSQL behind an opaque cookie, so reloading or restarting nginx or the tunnel does not sign anyone out. Because sign-in is not implemented yet, the available proof is a request in flight and a kept connection across systemctl reload nginx: both complete without a 5xx, and the next request on the same connection succeeds.
Verification
curl -sI http://<domain>/ # 301 to https://<domain>/
curl -sv https://<domain>/ -o /dev/null # valid chain, HTTP/2, Strict-Transport-Security
curl -s https://<domain>/some/deep/link # the SPA index.html
curl -s https://<domain>/api/v1/healthz # 200 from Go through both Nginx instances
openssl s_client -connect <EDGE_LISTEN_IP>:443 -servername <domain> -tls1_1 # handshake fails
openssl s_client -connect <EDGE_LISTEN_IP>:443 -servername <domain> -tls1_2 # works
When the local resolver does not return the public address, add --resolve <domain>:443:<EDGE_LISTEN_IP> to the curl commands.
Rollback
- Take the site off the air without touching the edge host's other services:
sudo rm /etc/nginx/conf.d/lincodex-https.conf && sudo nginx -t && sudo systemctl reload nginx. Port 80 then redirects to an HTTPS address that no longer answers, so removelincodex-http.conftoo if the redirect is unwanted.sudo systemctl disable --now nginxstops nginx entirely. - Remove the certificate:
sudo certbot delete --cert-name <domain>, and the hook file if nothing else uses it. Disablecertbot.timeronly if no other certificate depends on it. - Remove the firewall rules by number after
sudo ufw status numbered, checking the rule text, never the existing ones: the 80/tcp, 443/tcp, and tunnel UDP rules carry alincodexcomment. - Tunnel:
sudo systemctl disable --now awg-quick@awg-lincodexon both hosts, then remove/etc/systemd/system/awg-quick@awg-lincodex.service.d,/etc/systemd/system/docker.service.d/10-lincodex-awg.conf(app host),/etc/amnezia/amneziawg/awg-lincodex.*, and/usr/local/bin/amneziawg-go;sudo dpkg -r amneziawg-toolsremoves the tools. - App host: set
APP_HTTP_BIND=127.0.0.1in.envand runmake -C deploy upto publish the frontend on loopback again, ormake -C deploy downto stop the stack (volumes are kept). - Packages:
sudo apt-get remove nginx certbotleaves/etc/letsencryptin place; deleting it also deletes the private key.
Limits
This is one edge host and one app host. There is no failover, no external uptime check, and no rate limiting at the edge (the backend rate limits are separate and not implemented yet). The certificate covers only the one name, the site is IPv4 only, and the ACME account has no contact address. The tunnel carries no authentication beyond the AmneziaWG keys, and the obfuscation parameters raise the cost of blocking but are not a security control.
Services and images
Container images use moving latest or alpine tags where the upstream publishes them. Check the current Compose references when updating the stack. These tags can move; the release manifest records the actual image digests of a release. An SBOM is not produced yet. Application dependency lockfiles remain checked in separately.
| Component | Current image source | Principal upstream license |
|---|---|---|
| PostgreSQL | Docker Official Image, docker-library/postgres | PostgreSQL License for the server; packaging repository is MIT |
| SeaweedFS | chrislusf/seaweedfs | Apache-2.0 |
| Apache Kafka | apache/kafka, the Apache Kafka project's image | Apache-2.0 |
| Prometheus | prom/prometheus | Apache-2.0 |
| Loki | grafana/loki | AGPL-3.0-only by default; see LICENSING.md exceptions |
| Grafana Alloy | grafana/alloy | Apache-2.0 by default |
| Grafana | grafana/grafana | AGPL-3.0-only by default |
| Node exporter | prometheus/node_exporter | Apache-2.0 |
| PostgreSQL exporter | prometheus-community/postgres_exporter | Apache-2.0 |
| Docker socket proxy | Tecnativa/docker-socket-proxy | Apache-2.0 |
| BusyBox | busybox | GPL-2.0-only |
Upstream references: PostgreSQL image, Prometheus, Loki license details, Alloy license details, Grafana license details, node_exporter, postgres_exporter, socket proxy, BusyBox license.
These entries name the principal upstream project's license; they are not a complete inventory of every file in an image. Base OS packages and bundled dependencies may have separate terms. Before redistribution, inspect the exact image tag or digest, its notices, and an SBOM. This repository has no project-wide license.
The backend builds with Go 1.26.8; its runtime image is selected in backend/Dockerfile. Frontend and ML base images are selected in their Dockerfiles. Upstream sources include Docker Official Images, Distroless, and NGINX unprivileged images; inspect exact tags and layers before distribution.
Release manifest
A release manifest records what a verified local release consists of: the commit, the toolchain versions, the lockfile hashes, the image of every service with its actual digest, and which components a check really ran. Moving latest and alpine tags stay in Compose and in the Dockerfiles by agreement; the manifest pins what they resolved to at release time. The interface is make -C deploy release-manifest; the other release-* targets prepare its inputs and check its result:
make -C deploy release-build
make -C deploy release-smoke
make -C deploy release-e2e
make -C deploy release-manifest
make -C deploy release-manifest-check
release-buildbuildsbackend,frontend, andmlfrom their Dockerfiles and lockfiles through Compose and tags themlincodex.invalid/<service>:<tag>. The.invaliddomain never resolves, and the release overlays setpull_policy: never, so a missing release image is never pulled from a registry. Each Dockerfile takes its base images as*_IMAGEbuild arguments whose defaults are the agreed tags; the target resolves each base to its repository digest in the local image store and builds with<tag>@<digest>. A base image used throughCOPY --fromorRUN --mount=fromthat is not an earlier stage is refused, because it could not be pinned. Base and core service images are pulled only when missing locally;RELEASE_PULL=alwaysrefreshes every tag first. The target reads the source state again after the build and writesbuild.json(build arguments, base digests, image IDs) only if the commit and the working tree did not change during the build.release-smokeandrelease-e2erundeploy/scripts/smoke.shanddeploy/scripts/e2e.shwithLINCODEX_RELEASE_TAG, which only these targets set: the stack starts from the release images with--no-build --pull never, and only after every check passes does the script writeevidence-smoke.jsonorevidence-e2e.jsonwith the release tag, commit, working tree fingerprint, and the image IDs of the running containers. A failed run writes nothing. Evidence written after the checks passed stays even if the stack cleanup fails afterwards; the script still exits with an error then.release-manifestreads only local images, the build record, and the evidence; it pulls nothing. A missing image is listed as not present. Evidence or a build record that is malformed or was recorded for another tag, commit, or working tree state is not used; the manifest lists the rejected evidence underrejected_checks.release-manifest-checkchecks the structure of the manifest and scans it for secrets and machine data.release-upandrelease-downrun the core stack from the release images withENV_FILEandAPP_PROJECT, without building or pulling.make -C deploy release-manifest-verify RELEASE_VERIFY_PROJECT=<project>compares every running container of that Compose project with the manifest of the current tag, or withRELEASE_MANIFEST=<path>, by image ID. It prints the release status and exits with status 1 on a different digest, a missing service, or a service the manifest does not list.release-cleanremoves the locallincodex.invalid/*images and keeps the files indeploy/release/.
The release tag is the first 12 characters of the commit, with -dirty when the working tree differs from it. The working tree fingerprint is the Git tree ID written from a temporary index (seeded from HEAD, then git add -A), with line ending, file mode, symlink, and fsmonitor settings pinned. It covers modified, deleted, and untracked files, does not depend on diff settings, and leaves the real index untouched. All files go to deploy/release/<tag>/, which Git and the root .dockerignore ignore. Manifests are not committed: built image IDs depend on the machine, platform, and build time, and the manifest describes what this machine built and checked. Attach the manifest to the release instead.
Format
The manifest is JSON with sorted keys and schema lincodex.release-manifest/v1:
| Key | Content |
|---|---|
schema, generated_at |
Schema version and UTC generation time |
release |
tag, status (verified or unverified), scope (core), required_checks (smoke, e2e), and the reasons that keep it unverified |
source |
commit, dirty, the working tree fingerprint (git-tree:<id>, or null for a clean tree), and build_matches_source |
toolchains |
Go from go.mod, its toolchain directive, the GO_IMAGE default, GOTOOLCHAIN=local, the base image version, and the version recorded in the backend binary; Node and pnpm from .node-version, packageManager, the Dockerfile, and the base image; Python and uv from .python-version, requires-python, the Dockerfile, and the base image; matches_version_file for Node and Python; the Playwright package version |
lockfiles |
SHA-256 of backend/go.mod, backend/go.sum, frontend/package.json, frontend/pnpm-lock.yaml, ml/pyproject.toml, and ml/uv.lock |
checks, rejected_checks |
Accepted evidence with its scope, finish time, commit, fingerprint, and tool image, such as the Playwright image; rejected evidence with the reason |
components |
Each Compose service of core, ML, and monitoring and each missing component: group, kind (built, pulled, absent), the image (reference, present, image_id, repo_digest for the tag's repository, all repo_digests, platform, and allowlisted versions), for built images the Dockerfile, its hash, build arguments, and base images, and verification |
verification.status is one of:
verified: at least one accepted smoke or E2E run recorded this exact image ID for the service.verification.checkslists which. Only core services can be verified.not_verified: the image is absent, was not in an accepted passing run, or belongs to a group no release check starts. ML is built but no check starts it and it has no model; monitoring images are recorded only when present locally.missing: the component is planned but has no service or image in this repository: GPU inference, Judge0, and Qdrant.
The release is verified only when all of the following hold; otherwise release.reasons names each failed condition:
- the working tree is clean and the build record is well formed and matches the current source;
- every core image was built by
release-build, and every core pulled image has a registry digest; - both smoke and E2E evidence for the current source passed on the current image ID of every core component;
- every lockfile and every service Dockerfile exists;
- the Go pin is consistent and the backend binary reports the go.mod Go version;
- Node in the frontend build image equals
frontend/.node-version.
A Python version that differs from ml/.python-version is reported in matches_version_file but does not block the release, because ML is outside the verified scope. A moving node:alpine tag can therefore make a release unverified until .node-version is updated. A dirty tree is not refused: the manifest is written with unverified and the reason, so a local candidate can be checked before the commit.
Generating the manifest again for the same source, images, and evidence gives the same document apart from generated_at; the target says whether anything else changed since the previous manifest of the tag. Version fields are copied only from an allowlist of image variables and OCI labels. The manifest never contains environment values, .env content, container labels, mounts, local paths, user or host names; every file is scanned for those, for values of variables whose names suggest secrets (also as substrings and in base64), and for secret patterns before it is written, and release-manifest-check repeats the scan.
Go pin
go.mod declares go 1.26.8 without a separate toolchain line, the default GO_IMAGE is golang:1.26.8-alpine, and the build stage sets GOTOOLCHAIN=local, so a go.mod that asks for a newer Go fails the build instead of downloading another toolchain. make -C deploy check fails when these pins disagree or when a Dockerfile uses a base image that is not a pinnable build argument. The manifest also records the version read from the build information of the backend binary; to read it, the generator creates a container from the image without starting it, copies the binary out, and removes the container.
Not covered
- The manifest is not an SBOM, a license inventory, a signature, or a provenance attestation, and it is not pushed to a registry.
- The files in
deploy/release/are local and not tamper-proof; evidence is not signed and proves only what this machine recorded. - Git-ignored files are not part of the fingerprint. A build context still receives such files unless
.dockerignoreexcludes them. - Images are built for the local platform only. Versions without an image variable or label, such as Kafka, are identified only by digest.
verifiedmeans the image passed the recorded technical checks. Kafka publication, product workflows, ML, monitoring, backups, and production hosts are not checked.- CI runs
check-releaseas part ofmake -C deploy check, but not the release build, the release runs, or the manifest targets.
Observability configuration
Prometheus scrapes backend /metrics on port 9090, PostgreSQL exporter, Redis exporter on port 9121, SeaweedFS on port 9327, node exporter, itself, and the optional ML target. Loki uses a single-binary filesystem store with 168-hour retention. Grafana provisions Prometheus and Loki datasources from observability/grafana/provisioning/.
The five checked-in dashboard JSON files are maintained as project dashboards: Go runtime, PostgreSQL, Redis, SeaweedFS, and Linux system. The Redis dashboard covers availability, memory, cache hits/misses, evictions/expired keys, and client connections. The exporter collects aggregate metrics without scanning keys. The SeaweedFS dashboard covers availability, S3 request rate and duration, errors, disk, and memory; Prometheus retains only selected aggregate metrics without object paths. They were not copied from Grafana dashboard IDs. No external dashboard provenance or license is claimed for them.
The local monitoring stack is a single-node development/demo setup and provides no HA. Compose validation does not establish production retention, off-host backups, public access control, alert delivery, or core application behavior.
Workflow files exist in .github/workflows/. Their presence does not mean they have run on GitHub. Branch protection should require two checks: Required CI result from ci.yml and Required documentation result from docs.yml. See the testing guide for the difference between configuration validation, an infrastructure smoke, and product-flow tests.