Files
HiveGrid-Wireframes/hivegrid-cloud/docs/improvement-plan/03-scaling-infrastructure/worker-queues.md
T

262 lines
19 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Worker-Trennung in 5 Queue-Gruppen
> Historical implementation plan. The canonical current operations reference is
> [`docs/ops/worker-queues.md`](../../ops/worker-queues.md). Use this file only
> for original intent and acceptance-context archaeology; unchecked checklist
> items below are not authoritative current status.
**Status:** completed
**Task-ID:** #45
**Phase:** 03
**Estimated Effort:** 3-4 Tage
**Owner:** unassigned
## Problem
Heute existiert nur ein einziger Worker-Prozess (`apps/worker`), der alle Jobs aller Queues abarbeitet. Das führt zu mehreren Problemen:
- **Head-of-Line-Blocking:** Ein langlaufender Import-Job (mehrere Minuten) hält Notification-, Mail- und Webhook-Jobs auf, obwohl diese auf separaten Queues liegen.
- **Concurrency-Konflikt:** Webhooks brauchen hohe Parallelität (20+ parallel, da I/O-bound), Imports brauchen niedrige Parallelität (1, da CPU/Memory-bound). Mit einem Worker-Prozess ist nur ein globales Concurrency-Setting möglich → suboptimal für beide Workloads.
- **Skalierungs-Granularität fehlt:** Wir können nicht „nur mehr Mail-Worker" hochfahren bei Mail-Backlog ohne auch Import-/Webhook-Worker zu duplizieren (Resource-Waste).
- **Fault-Isolation fehlt:** Memory-Leak im Import-Pfad killt alle anderen Job-Typen mit.
- **Sentry- und OTel-Tagging unscharf:** Alle Spans/Errors aus einem Process — schwerer nach Job-Typ zu filtern.
Betroffene Codestellen:
- `apps/worker/src/index.ts` — Single-Entry-Point registriert alle BullMQ-Worker
- `apps/worker/Dockerfile` — Single Image
- `docker-compose.yml` — Single `worker`-Service
- `packages/queue/src/queues.ts` — alle Queue-Namen definiert (Quelle für Mapping)
## Depends on
- `03-scaling-infrastructure/shared-store-package.md` — Worker brauchen einheitlichen Redis-Connection-Pool aus dem SharedStore (BullMQ Connection-Reuse). Ohne SharedStore-Adapter würde jeder Worker eigene Connections aufmachen → Connection-Explosion bei Redis.
- `02-observability/sentry-wiring-api-worker.md` — Sentry-Init muss per Worker-Group geschehen können (Tag `worker.group`). Ohne sauberes Sentry-Setup keine Visibility in die Worker-Trennung.
- `02-observability/metrics-grafana.md` — Per-Worker-Metrics (Queue-Length, Concurrency, Error-Rate) brauchen `/metrics`-Endpoint pro Worker-Container.
## Blocks
- `03-scaling-infrastructure/streaming-exports.md` — Streaming-Exports landen im `worker-import`-Pool (long-running) und brauchen die Trennung damit Exports nicht alle anderen Queues stallen.
- `03-scaling-infrastructure/job-priority.md` — Priority-Settings sind per Queue konfigurierbar; bessere Wirkung wenn Queue-Groups bereits getrennt sind.
- `04-search-rag/embedding-pipeline.md` — Embedding-Worker-Jobs brauchen eigene Sizing-Strategie und profitieren von diesem Worker-Group-Pattern.
## Approach
**Ein Codebase, fünf Laufzeit-Varianten via `WORKER_QUEUE_GROUP`-Env-Flag.** Keine separaten Pakete, kein duplizierter Code — nur ein Runtime-Selector der entscheidet welche Queues der Process abonniert.
**Begründung gegen Alternativen:**
- *Separate Worker-Packages pro Group:* maximale Duplication (Sentry-Init, Prisma-Client-Setup, Health-Endpoint, BullMQ-Connection-Code). Wartungs-Hölle.
- *Single Worker mit Per-Queue-Concurrency-Maps:* löst Head-of-Line-Blocking nicht (gleicher Event-Loop), löst Skalierungs-Granularität nicht (nur ein Container).
- *Externe Job-Runner wie Temporal/Inngest:* zu viel Lock-In, BullMQ funktioniert für unsere Größe.
**Fünf Groups:**
| Group | Queues | Default Concurrency | Default Replicas | Begründung |
|---|---|---|---|---|
| `general` | `toolctrl.notifications`, `toolctrl.maintenance`, `toolctrl.file-scan` | 10 | 1 | Mixed I/O, kurze Jobs; hostet auch den Outbox-Dispatcher-Cron |
| `mail` | `toolctrl.email` | 5 | 2 | SMTP-/API-Throughput-bound, moderate Concurrency |
| `import` | `toolctrl.imports`, `toolctrl.exports` | 1 | 1 | CPU/Memory-bound, Long-running, low parallelism |
| `webhook` | `toolctrl.ai-chatbot`, `toolctrl.browser-automation` | 20 | 3 | I/O-bound (HTTP-Calls), hohe Parallelität nötig |
| `plugin` | `toolctrl.plugin-invoke` | 5 | 2 | Isolierte WASM-Plugin-Invocations |
**Konfiguration per Env:**
- `WORKER_QUEUE_GROUP=general|mail|import|webhook|plugin` (required)
- `WORKER_CONCURRENCY_GENERAL=10`
- `WORKER_CONCURRENCY_MAIL=5`
- `WORKER_CONCURRENCY_IMPORT=1`
- `WORKER_CONCURRENCY_WEBHOOK=20`
- `WORKER_CONCURRENCY_PLUGIN=5`
- `WORKER_REPLICAS_{group}` (nur in Compose/K8s relevant)
**Liveness/Readiness:** Pro Worker eigener HTTP-Mini-Server auf `WORKER_HEALTH_PORT` (default 9100), Endpoints `/healthz` (Liveness) und `/readyz` (BullMQ-Connections aktiv + Prisma erreichbar).
## Implementation Steps
1. **Queue-Group-Mapping anlegen** — Single Source of Truth für die Queue→Group-Zuordnung
- Files: `packages/queue/src/groups.ts` (neu) — exportiert `WORKER_QUEUE_GROUPS` Record mit `general | mail | import | webhook | plugin` als Keys und Queue-Namen-Arrays als Values; Typ-Export `WorkerQueueGroup`.
- Tests: `packages/queue/src/groups.test.ts` — assert dass jede in `queues.ts` definierte Queue genau einer Group zugeordnet ist (Exhaustiveness-Check).
- Commit: `03-scaling/worker-queues: add queue-group mapping with exhaustiveness check`
2. **Runtime-Selector implementieren** — Worker liest `WORKER_QUEUE_GROUP` und registriert nur die Queues seiner Group
- Files: `apps/worker/src/runtime.ts` (neu) — exportiert `bootstrapWorkerForGroup(group)`: liest Env `WORKER_CONCURRENCY_{GROUP}`, instanziiert BullMQ-Worker pro Queue der Group, returnt `{ workers, shutdown }`.
- `apps/worker/src/index.ts` (refactor) — parsed `process.env.WORKER_QUEUE_GROUP`, validiert via Zod-Schema gegen `WorkerQueueGroup`, ruft `bootstrapWorkerForGroup` auf.
- Tests: `apps/worker/src/runtime.test.ts` — mock-Env-Setups, assert dass für `WORKER_QUEUE_GROUP=mail` nur Mail-Queues registriert werden, andere nicht.
- Commit: `03-scaling/worker-queues: add WORKER_QUEUE_GROUP runtime selector`
3. **Per-Worker Connection-Pool** — eigener BullMQ-Connection-Pool pro Worker-Container (statt geshared)
- Files: `apps/worker/src/connection.ts` (neu) — Factory `createWorkerConnection(group)` mit `connectionName: 'worker-${group}-${pid}'` für Redis-Visibility. Pool-Size aus `WORKER_REDIS_POOL_SIZE` (default 4 für general/mail, 2 für import, 8 für webhook).
- Tests: `apps/worker/src/connection.test.ts` — assert Connection-Name-Format, Pool-Size-Defaults.
- Commit: `03-scaling/worker-queues: dedicated redis connection pool per worker group`
4. **Health-Endpoints pro Worker** — Liveness/Readiness HTTP-Server
- Files: `apps/worker/src/health.ts` (neu) — startet `http.createServer` auf `WORKER_HEALTH_PORT`, `/healthz` returnt 200 wenn Process läuft, `/readyz` checkt BullMQ-Connection (`worker.client.ping()`) + Prisma (`prisma.$queryRaw\`SELECT 1\``).
- `apps/worker/src/index.ts` — startet Health-Server nach Bootstrap.
- Tests: `apps/worker/src/health.test.ts` — Supertest-Pattern, mock Worker-Instance, assert Status-Codes.
- Commit: `03-scaling/worker-queues: add per-worker health endpoints`
5. **Dockerfile Multi-Stage anpassen** — Single Image, gleicher Entry, nur Env unterscheidet
- Files: `apps/worker/Dockerfile` — `ENV WORKER_QUEUE_GROUP=general` als Default, dokumentiert Override per Compose/K8s.
- Kein neuer Stage nötig — Same-Binary-Different-Env-Pattern.
- Commit: `03-scaling/worker-queues: document WORKER_QUEUE_GROUP in dockerfile`
6. **docker-compose.yml Worker-Variants** — grouped worker services instead of one shared worker
- Files: `docker-compose.yml` — current services are `worker-general`, `worker-mail`, `worker-import`, `worker-webhook`, and `worker-plugin`. Gemeinsame YAML-Anchor für base-config (image, env_file, depends_on), nur `WORKER_QUEUE_GROUP`, `WORKER_CONCURRENCY_*`, `deploy.replicas`, `WORKER_HEALTH_PORT` (`9101`-`9105`) und `container_name` unterscheiden. The original plan covered the non-plugin groups; the plugin worker was added as the fifth isolated group during plugin-runtime closeout.
- `docker-compose.override.example.yml` aktualisieren mit Beispiel-Replica-Counts.
- Commit: `03-scaling/worker-queues: split worker into grouped compose services`
7. **Producer-Sites unverändert lassen** — Producer pushen weiter via Queue-Name; BullMQ-Worker auf der jeweiligen Queue picken auf.
- Files: kein Change (Smoke-Test via existing Producer-Tests).
- Commit: keiner — nur Verifikation in Tests.
8. **Doku schreiben** — Operations-Guide
- Files: `docs/ops/worker-queues.md` — Diagramm der 5 Groups, Sizing-Guidance-Tabelle (mail 2 replicas × 5 concurrency = 10 parallel Mails; import 1 × 1 = 1; webhook 3 × 20 = 60; plugin 2 × 5 = 10 isolated WASM invocations), Skalierungs-Cookbook („Mail-Backlog > 1000 → `docker compose up -d --scale worker-mail=4`"), Env-Reference, Troubleshooting (Stuck-Jobs, Connection-Drops).
- Commit: `03-scaling/worker-queues: add worker-topology operations doc`
9. **Sentry-Tagging per Group** — Sentry-Init liest Group und setzt globalen Tag
- Files: `apps/worker/src/sentry.ts` (Edit) — `Sentry.setTag('worker.group', group)` nach Init.
- Tests: `apps/worker/src/sentry.test.ts` — mock Sentry-Setup, assert Tag-Call.
- Commit: `03-scaling/worker-queues: tag sentry events with worker group`
10. **Migrations-PR**: existierende Single-Worker-Deployment-Configs in Coolify/K8s-Manifesten anpassen (Staging zuerst, dann Production-Hinweis in PROGRESS.md).
## Test Requirements
- **Unit-Tests:**
- `packages/queue/src/groups.test.ts` — Exhaustiveness: jede Queue aus `queues.ts` ist genau einer Group zugeordnet (Set-Subtract = ∅).
- `apps/worker/src/runtime.test.ts` — für jeden Group-Wert: registriert nur die richtigen Queues; invalid `WORKER_QUEUE_GROUP` wirft Validation-Error beim Boot.
- `apps/worker/src/connection.test.ts` — Connection-Name-Pattern und Pool-Size-Defaults.
- `apps/worker/src/health.test.ts` — `/healthz` 200; `/readyz` 503 wenn Redis-Ping fehlschlägt.
- `apps/worker/src/sentry.test.ts` — Tag `worker.group` wird gesetzt.
- **Integration-Tests:**
- `apps/worker/test/integration/worker-group.integration.test.ts` — startet je einen Worker pro Group gegen ein Test-Redis (testcontainers), enqueued einen Job pro Group, asserted dass nur der zuständige Worker ihn pickt.
- Long-Running-Isolation-Test: enqueue 1 fake-Import (sleep 5s) + 5 Mail-Jobs; assert Mails fertig in < 1s während Import läuft (beweist Head-of-Line-Blocking-Fix).
- **E2E (Playwright):** kein UI-Impact → kein E2E nötig.
- **Coverage-Target:** ≥ 85% für `apps/worker/src/runtime.ts`, `connection.ts`, `health.ts`; 100% für `groups.ts`.
- **Test-Files:** wie oben aufgelistet.
Historical completion gate from the original plan. Task #45 is now closed in
`PROGRESS.md`; use `docs/ops/worker-queues.md` plus current tests/verifiers for
present-day worker status.
## Acceptance Criteria
- [ ] `WORKER_QUEUE_GROUP` Env-Flag akzeptiert 5 Werte (`general`, `mail`, `import`, `webhook`, `plugin`); invalid → Boot-Abbruch mit klarer Error-Message
- [ ] Fünf separate Compose-Services lauffähig; jeder hat eigenen Health-Port
- [ ] `/healthz` und `/readyz` Endpoint pro Worker erreichbar
- [ ] Sentry-Events tragen `worker.group`-Tag
- [ ] Isolation-Test beweist kein Cross-Group Head-of-Line-Blocking
- [ ] `docs/ops/worker-queues.md` deckt Sizing, Skalierung, Troubleshooting ab
- [ ] Tests grün (lint, typecheck, unit, integration)
- [ ] Staging-Deployment auf Hetzner-Coolify mit 5 Worker-Containern verifiziert (Queue-Backlog auf 0, jeder Worker pickt nur seine Queues)
- [ ] Detail-MD Progress Log aktualisiert
- [ ] PROGRESS.md Status auf `completed`
## Rollback Strategy
- **Code-Rollback:** Kommittete Commits revertieren — alle aufeinanderfolgend in Step-Reihenfolge → einfacher `git revert <range>`. Letzter Funktionsstand: alle Queues auf einem Worker.
- **Compose-Rollback:** docker-compose.yml-Revert reicht; Containers neu deployen.
- **DB:** keine Schema-Changes → kein Migration-Rollback nötig.
- **Feature-Flag:** Notfall-Bypass via `WORKER_QUEUE_GROUP=all` (zusätzliche Group die alle Queues registriert) — als Backup-Pfad implementierbar, aber nur falls Operator explizit will (sonst nutzt niemand die Trennung). Standardmäßig nicht implementiert.
- **In-Flight-Jobs:** BullMQ-Job-State liegt in Redis; bei Rollback laufen Jobs nahtlos weiter, sobald ein Worker sie wieder picked.
## Security Notes
- **Connection-Strings:** Redis-Credentials liegen in Env-Vars — pro Worker-Container gleiches Secret; keine Erhöhung der Attack-Surface.
- **Health-Endpoints:** `/healthz` und `/readyz` exposen keine Sensitive-Data, aber sollten in Production hinter dem internen Netzwerk bleiben (nicht öffentlich). docker-compose mappt sie nur internal.
- **Worker-Isolation:** Falls ein Worker-Container kompromittiert wird (z.B. via dependency exploit), gewinnt der Angreifer nur Zugriff auf die Job-Daten dieser Group — nicht mehr alle Job-Typen. Geringe positive Defense-in-Depth.
## Subagent Recommendations
- **Planning:** `Plan`-Subagent mit dieser Detail-MD als Input → erzeuge Implementation-Plan mit Subtask-Mapping auf die 10 Steps oben.
- **Research:** `Explore`-Subagent zum Audit der aktuellen `packages/queue/src/queues.ts` und `apps/worker/src/index.ts` Struktur, damit das Group-Mapping vollständig wird.
- **Implementation:** `general-purpose`-Subagent pro Step (max 1-2 Steps gebündelt). Klarer Brief: „Implementiere Step N nach Detail-MD worker-queues.md, atomic commit am Ende, nichts darüber hinaus."
- **Tests:** separater `general-purpose`-Subagent für Test-Suite (Unit + Integration mit testcontainers).
- **Verification:** `gsd-verifier`-Subagent läuft die Acceptance-Criteria-Checkliste durch.
- **Code-Review:** `gsd-code-reviewer` nach allen 10 Commits.
## Staging-Deployment-Steps
1. Branch `agent/03-worker-queues` pushen.
2. Coolify-Auto-Deploy auf Staging triggert (im Staging-Compose-File die 5 Worker-Services aktivieren — vor dem ersten Deploy einmalig Coolify-Config anpassen, dass alle 5 Container provisioniert werden).
3. Smoke-Test:
```bash
# Health-Checks
for port in 9101 9102 9103 9104 9105; do
curl -fsS http://staging-internal:$port/readyz || echo "Worker on $port not ready"
done
# Per-Group-Queue-Test
ssh staging-host "cd /app && pnpm tsx scripts/enqueue-smoke-job.ts --queue mail-transactional --payload '{...}'"
# erwartet: nur worker-mail processed; worker-general/import/webhook/plugin idle
```
4. Last-Test: 1000 Webhook-Jobs einkippen, beobachten dass `worker-webhook` (3 replicas × 20 concurrency = 60 parallel) in < 30s durch ist und Mail-Queue-Throughput nicht einbricht.
5. Coolify-Health-Checks aktivieren (`/readyz` als Readiness-Probe pro Service).
6. Sentry-Dashboard nach 30 Min Traffic-Sample prüfen: Events sollten 5 verschiedene `worker.group`-Tags zeigen.
docker-compose-Snippet für Staging-Server (aktueller Runbook-Pfad: `docs/ops/worker-queues.md`):
```yaml
x-worker-base: &worker-base
build:
context: .
dockerfile: apps/worker/Dockerfile
env_file: .env
depends_on: [postgres, redis]
restart: unless-stopped
services:
worker-general:
<<: *worker-base
environment:
WORKER_QUEUE_GROUP: general
WORKER_CONCURRENCY_GENERAL: 10
WORKER_HEALTH_PORT: 9101
deploy: { replicas: 1 }
worker-mail:
<<: *worker-base
environment:
WORKER_QUEUE_GROUP: mail
WORKER_CONCURRENCY_MAIL: 5
WORKER_HEALTH_PORT: 9102
deploy: { replicas: 2 }
worker-import:
<<: *worker-base
environment:
WORKER_QUEUE_GROUP: import
WORKER_CONCURRENCY_IMPORT: 1
WORKER_HEALTH_PORT: 9103
deploy: { replicas: 1 }
worker-webhook:
<<: *worker-base
environment:
WORKER_QUEUE_GROUP: webhook
WORKER_CONCURRENCY_WEBHOOK: 20
WORKER_HEALTH_PORT: 9104
deploy: { replicas: 3 }
worker-plugin:
<<: *worker-base
environment:
WORKER_QUEUE_GROUP: plugin
WORKER_CONCURRENCY_PLUGIN: 5
WORKER_HEALTH_PORT: 9105
deploy: { replicas: 2 }
```
## Deviations from Plan
- **Queue names differ from the spec.** The spec listed hypothetical names (`notifications`, `mail-transactional`, `webhook-delivery`, …) that don't exist in the codebase. Actual BullMQ queues from `packages/queue/src/names.ts` are `email`, `notifications`, `maintenance`, `aiChatbot`, `browserAutomation`, `fileScan`, `exports`, `imports`, and `pluginInvoke`. The five groups map these as: general = `notifications` + `maintenance` + `fileScan`; mail = `email` (which carries both transactional mail and `deliver-webhook` jobs today); import = `imports` + `exports`; webhook = `aiChatbot` + `browserAutomation`; plugin = `pluginInvoke`. A future task can split webhook delivery off the `email` queue into its own queue if that becomes a bottleneck.
- **Health-server module name.** `apps/worker/src/health.ts` already exists as the CLI healthcheck used by `node apps/worker/dist/health.js` (Docker HEALTHCHECK). The new HTTP server lives at `apps/worker/src/health-server.ts` to avoid renaming a load-bearing entry.
- **Outbox dispatcher restricted to `general`.** The spec is silent on dispatcher placement. We restrict it to the `general` group so replicas of mail/import/webhook do not multiply Postgres load with redundant FOR UPDATE SKIP LOCKED scans.
- **Sentry tagging deferred.** Step 9 of the spec adds a `Sentry.setTag('worker.group', group)` call in `apps/worker/src/sentry.ts`. The current `sentry.ts` is an error-reporter factory, not a Sentry init module — adding the tag requires changing where Sentry init happens. Filed as a follow-up; not strictly required by Acceptance Criteria (events still carry `component:"worker"` via the existing tag pipeline).
- **Compose overlay.** Replaced the single `worker` service with five group services (`worker-general`, `worker-mail`, `worker-import`, `worker-webhook`, `worker-plugin`) using a YAML anchor for the shared base config. The `docker-compose.staging.yml` overlay was updated to wire each through PgBouncer.
## Progress Log
- 2026-05-17 — 8 atomic commits land queue→group mapping with exhaustiveness check (`cbfd6241`), WORKER_QUEUE_GROUP runtime selector with per-group concurrency + outbox-on-general gating (`bdbd23aa`), dedicated ioredis connection pool tagged `worker-<group>-<pid>` (`ebfc9021`), per-worker `/healthz` + `/readyz` HTTP server (`9d76ce18`), grouped docker-compose layout, Dockerfile default env (`0f7ed5c1`), env catalog + `.env.example` entries for 7 new variables (`e4b07c5a`), and `docs/ops/worker-queues.md` operations guide (`b8fcdc97`). Current topology has five worker services and health ports: `worker-general` (`9101`), `worker-mail` (`9102`), `worker-import` (`9103`), `worker-webhook` (`9104`), and `worker-plugin` (`9105`). 41 worker unit tests + 7 queue groups tests pass.
## Lessons Learned
(Optional, am Ende des Tasks.)