19 KiB
Worker-Trennung in 5 Queue-Gruppen
Historical implementation plan. The canonical current operations reference is
docs/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-Workerapps/worker/Dockerfile— Single Imagedocker-compose.yml— Singleworker-Servicepackages/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 (Tagworker.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 imworker-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=10WORKER_CONCURRENCY_MAIL=5WORKER_CONCURRENCY_IMPORT=1WORKER_CONCURRENCY_WEBHOOK=20WORKER_CONCURRENCY_PLUGIN=5WORKER_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
-
Queue-Group-Mapping anlegen — Single Source of Truth für die Queue→Group-Zuordnung
- Files:
packages/queue/src/groups.ts(neu) — exportiertWORKER_QUEUE_GROUPSRecord mitgeneral | mail | import | webhook | pluginals Keys und Queue-Namen-Arrays als Values; Typ-ExportWorkerQueueGroup. - Tests:
packages/queue/src/groups.test.ts— assert dass jede inqueues.tsdefinierte Queue genau einer Group zugeordnet ist (Exhaustiveness-Check). - Commit:
03-scaling/worker-queues: add queue-group mapping with exhaustiveness check
- Files:
-
Runtime-Selector implementieren — Worker liest
WORKER_QUEUE_GROUPund registriert nur die Queues seiner Group- Files:
apps/worker/src/runtime.ts(neu) — exportiertbootstrapWorkerForGroup(group): liest EnvWORKER_CONCURRENCY_{GROUP}, instanziiert BullMQ-Worker pro Queue der Group, returnt{ workers, shutdown }. apps/worker/src/index.ts(refactor) — parsedprocess.env.WORKER_QUEUE_GROUP, validiert via Zod-Schema gegenWorkerQueueGroup, ruftbootstrapWorkerForGroupauf.- Tests:
apps/worker/src/runtime.test.ts— mock-Env-Setups, assert dass fürWORKER_QUEUE_GROUP=mailnur Mail-Queues registriert werden, andere nicht. - Commit:
03-scaling/worker-queues: add WORKER_QUEUE_GROUP runtime selector
- Files:
-
Per-Worker Connection-Pool — eigener BullMQ-Connection-Pool pro Worker-Container (statt geshared)
- Files:
apps/worker/src/connection.ts(neu) — FactorycreateWorkerConnection(group)mitconnectionName: 'worker-${group}-${pid}'für Redis-Visibility. Pool-Size ausWORKER_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
- Files:
-
Health-Endpoints pro Worker — Liveness/Readiness HTTP-Server
- Files:
apps/worker/src/health.ts(neu) — startethttp.createServeraufWORKER_HEALTH_PORT,/healthzreturnt 200 wenn Process läuft,/readyzcheckt 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
- Files:
-
Dockerfile Multi-Stage anpassen — Single Image, gleicher Entry, nur Env unterscheidet
- Files:
apps/worker/Dockerfile—ENV WORKER_QUEUE_GROUP=generalals 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
- Files:
-
docker-compose.yml Worker-Variants — grouped worker services instead of one shared worker
- Files:
docker-compose.yml— current services areworker-general,worker-mail,worker-import,worker-webhook, andworker-plugin. Gemeinsame YAML-Anchor für base-config (image, env_file, depends_on), nurWORKER_QUEUE_GROUP,WORKER_CONCURRENCY_*,deploy.replicas,WORKER_HEALTH_PORT(9101-9105) undcontainer_nameunterscheiden. 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.ymlaktualisieren mit Beispiel-Replica-Counts.- Commit:
03-scaling/worker-queues: split worker into grouped compose services
- Files:
-
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.
-
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
- Files:
-
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
- Files:
-
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 ausqueues.tsist genau einer Group zugeordnet (Set-Subtract = ∅).apps/worker/src/runtime.test.ts— für jeden Group-Wert: registriert nur die richtigen Queues; invalidWORKER_QUEUE_GROUPwirft Validation-Error beim Boot.apps/worker/src/connection.test.ts— Connection-Name-Pattern und Pool-Size-Defaults.apps/worker/src/health.test.ts—/healthz200;/readyz503 wenn Redis-Ping fehlschlägt.apps/worker/src/sentry.test.ts— Tagworker.groupwird 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ürgroups.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_GROUPEnv-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
/healthzund/readyzEndpoint pro Worker erreichbar- Sentry-Events tragen
worker.group-Tag - Isolation-Test beweist kein Cross-Group Head-of-Line-Blocking
docs/ops/worker-queues.mddeckt 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:
/healthzund/readyzexposen 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 aktuellenpackages/queue/src/queues.tsundapps/worker/src/index.tsStruktur, 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-reviewernach allen 10 Commits.
Staging-Deployment-Steps
- Branch
agent/03-worker-queuespushen. - 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).
- Smoke-Test:
# 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 - 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. - Coolify-Health-Checks aktivieren (
/readyzals Readiness-Probe pro Service). - 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):
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 frompackages/queue/src/names.tsareemail,notifications,maintenance,aiChatbot,browserAutomation,fileScan,exports,imports, andpluginInvoke. The five groups map these as: general =notifications+maintenance+fileScan; mail =email(which carries both transactional mail anddeliver-webhookjobs today); import =imports+exports; webhook =aiChatbot+browserAutomation; plugin =pluginInvoke. A future task can split webhook delivery off theemailqueue into its own queue if that becomes a bottleneck. - Health-server module name.
apps/worker/src/health.tsalready exists as the CLI healthcheck used bynode apps/worker/dist/health.js(Docker HEALTHCHECK). The new HTTP server lives atapps/worker/src/health-server.tsto avoid renaming a load-bearing entry. - Outbox dispatcher restricted to
general. The spec is silent on dispatcher placement. We restrict it to thegeneralgroup 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 inapps/worker/src/sentry.ts. The currentsentry.tsis 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 carrycomponent:"worker"via the existing tag pipeline). - Compose overlay. Replaced the single
workerservice with five group services (worker-general,worker-mail,worker-import,worker-webhook,worker-plugin) using a YAML anchor for the shared base config. Thedocker-compose.staging.ymloverlay 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 taggedworker-<group>-<pid>(ebfc9021), per-worker/healthz+/readyzHTTP server (9d76ce18), grouped docker-compose layout, Dockerfile default env (0f7ed5c1), env catalog +.env.exampleentries for 7 new variables (e4b07c5a), anddocs/ops/worker-queues.mdoperations guide (b8fcdc97). Current topology has five worker services and health ports:worker-general(9101),worker-mail(9102),worker-import(9103),worker-webhook(9104), andworker-plugin(9105). 41 worker unit tests + 7 queue groups tests pass.
Lessons Learned
(Optional, am Ende des Tasks.)