Status: Active — Phase 2 dev complete; production cutover in progress Author: Engineering Last updated: June 2026 Supersedes target style of: docs/architecture.md §12 (Future Roadmap)
- Goal & Scope
- Decisions (Locked)
- Target Architecture
- Microservices Patterns Applied
- Service Boundaries
- Messaging Topology (RabbitMQ)
- Orchestrator Design (Saga Coordinator)
- Worker Design (AMQP Consumers)
- End-to-End Data Flow
- Cancellation, Retries & Failure Handling
- Data Ownership Plan
- Migration Plan (Phased)
- Kubernetes & Scaling
- Risks & Mitigations
- Appendix: Message Contracts
Migrate DabljaAR from a Celery-driven modular monolith to an event-driven microservices architecture composed of six independently deployable units:
frontend · backend · media · stt · nmt · tts
The dubbing pipeline (STT → NMT → TTS → merge) is coordinated by the Go orchestrator over RabbitMQ, replacing Celery pipeline transport (apply_async chains, the NMT chord, and the TTS Redis counter). Standalone POST /api/tts/synthesize is proxied to tts-service over HTTP in the microservices stack (legacy Celery path remains optional via ENABLE_CELERY_TTS=true).
Primary objective: ship the migration as fast as possible while keeping the door open for stricter data isolation later.
In scope: transport swap (Celery → AMQP), orchestrator wiring, worker refactor to consumers, NMT/TTS internal fan-out, deployment topology.
Out of scope (this phase): database-per-service split (Phase 3), event sourcing, frontend rewrite (stays polling-based).
These were explicitly chosen and drive the rest of this document.
| # | Decision | Choice | Rationale |
|---|---|---|---|
| D1 | Job/result persistence (Phase 1) | Workers write DB directly | Reuse existing BaseJobTask DB logic; only the transport changes. Fastest path. |
| D2 | Celery replacement | Event-driven: RabbitMQ + Go orchestrator | ~80% already built; fits long-running jobs. |
| D3 | NMT fan-out | Internal to NMT service | One message in, full translation out. No distributed chord. |
| D4 | TTS fan-out | Internal to TTS service | One message in, combined audio out. No Redis counter. |
| D5 | Partial pipelines (output_type) |
Orchestrator reads output_type and decides next stage |
Dynamic transition table matches current product behavior. |
| D6 | Media preprocessing | Pre-pipeline step | Backend triggers media, then publishes job.created. Orchestrator stays focused on dubbing. |
| D7 | Stage child-job creation | Orchestrator creates next child job, then publishes job.start.X with that child job_id |
Centralizes the state machine; workers stay dumb. |
| D8 | Cancellation | Cooperative cancel via DB flag | Orchestrator skips cancelled pipelines; workers check at stage/segment boundaries. |
| D9 | Database (Phase 1) | Shared DB (Option 1) → Orchestrator-owned (Option 3) after K8s deploy | Defer the hard split; unblock everything else now. |
flowchart TB
FE["frontend (React)"] -->|HTTPS or JSON| API["backend (FastAPI)"]
API -->|"BackgroundTasks preprocess"| API
API -->|"publish job.created"| MQ[("RabbitMQ\ndablja.jobs.exchange")]
ORCH["orchestrator (Go)\nsaga coordinator"]
MQ <--> ORCH
MQ -->|job.start.stt| STT["stt service"]
MQ -->|job.start.nmt| NMT["nmt service"]
MQ -->|job.start.tts| TTS["tts service"]
MQ -->|job.start.merge| MERGE["media-service\n(merge stage, :8003)"]
STT -->|job.results.stt| MQ
NMT -->|job.results.nmt| MQ
TTS -->|job.results.tts| MQ
MERGE -->|job.results.merge| MQ
API --> PG[("PostgreSQL\nshared - Phase 1")]
ORCH --> PG
STT --> PG
NMT --> PG
TTS --> PG
MERGE --> PG
STT --> S3[("MinIO / S3\nclaim-check store")]
TTS --> S3
MERGE --> S3
Key change vs today: stages no longer call each other (apply_async). Each worker only knows how to consume job.start.<stage> and publish job.results.<stage>. The orchestrator is the only component that knows pipeline order.
This is the explicit pattern catalog the design follows, with where each is realized.
| Pattern | Where / How |
|---|---|
| Orchestration-based Saga | The Go orchestrator is the saga coordinator. Each stage is a saga step; it advances on job.results.* and marks the parent FAILED on any step failure. See §7. |
| Asynchronous Messaging / Event-Driven | All inter-service pipeline communication is AMQP messages on a topic exchange. No synchronous stage-to-stage HTTP. |
| Competing Consumers | Each stage queue (job.start.stt, etc.) is consumed by N identical worker replicas. Throughput scales by adding replicas. |
| Claim Check | Large artifacts (audio, video, TTS wavs) live in MinIO/S3. Messages carry only object keys + job_id, never payloads. Keeps messages small and the broker fast. |
| Correlation Identifier | job_id correlates every message across stages and DB rows. |
| Idempotent Consumer | Workers must tolerate redelivery (RabbitMQ at-least-once). Re-running a stage on the same job_id overwrites the same DB row / S3 key deterministically. See §10. |
| Dead Letter Queue | Poison messages route to dablja.jobs.dlx → orchestrator.dlq (already implemented in manager.go). |
| Health Check API | Orchestrator exposes /health and /readiness; every service gets the same for K8s probes. |
| Externalized Configuration | All endpoints/secrets via env vars (existing Settings pattern); K8s ConfigMap/Secret. |
| Strangler Fig | Migration is incremental: workers move off Celery one queue at a time while the monolith keeps running. See §12. |
| Shared Database (transitional) | Phase 1 only — explicitly acknowledged as a transitional anti-pattern, retired in Phase 3 (Database-per-Service / orchestrator-owned). |
| API Gateway / Ingress | K8s Ingress fronts backend and frontend; AI services are cluster-internal only. |
Note on Saga compensation: dubbing stages are forward-only with no external side effects to undo (outputs are just S3 objects). So "compensation" is simply: mark the pipeline
FAILED, stop advancing, and leave orphaned S3 objects for a GC sweep. We do not need rollback transactions.
| Service | Owns | Inbound | Outbound | Runtime |
|---|---|---|---|---|
| frontend | UI | — | REST to backend | React/Vite |
| backend | auth, users, billing, videos, media preprocess (D6), job creation, status reads | REST | job.created, DB |
FastAPI |
| media-service | final merge mux only (stage.merge) |
job.start.merge |
DB, S3, job.results.merge |
Python + ffmpeg |
| stt | Whisper transcription | job.start.stt |
DB, job.results.stt |
Python + faster-whisper |
| nmt | NLLB translation incl. internal segment fan-out + Groq length adjust | job.start.nmt |
DB, job.results.nmt |
Python + transformers |
| tts | SILMA synthesis incl. internal per-segment loop + audio combine | job.start.tts |
DB, S3, job.results.tts |
Python + silma-tts |
| orchestrator | pipeline state machine, child-job creation, parent status | job.created, job.results.* |
job.start.*, DB |
Go |
Media preprocess (audio extract, thumbnail) runs in backend via FastAPI BackgroundTasks — not via AMQP. stage.media / job.start.media is not implemented (future optional path). Merge lives in media-service on port 8003.
Mapping from current modules: app/stt → stt-service, app/nmt → nmt-service, app/tts → tts-service, merge mux → media-service, app/media preprocess stays in backend.
Reuses the exchange/DLX already declared in orchestrator/internal/pipeline/manager.go.
Exchange: dablja.jobs.exchange (topic, durable)
DLX: dablja.jobs.dlx (direct, durable)
Routing keys (orchestrator -> workers):
job.start.media job.start.stt job.start.nmt job.start.tts job.start.merge
Routing keys (workers -> orchestrator):
job.results.media job.results.stt job.results.nmt job.results.tts job.results.merge
Trigger (backend -> orchestrator):
job.created
| Queue | Bound to | Consumer | Notes |
|---|---|---|---|
orchestrator.new_jobs |
job.created |
orchestrator | existing |
orchestrator.results |
job.results.* |
orchestrator | existing |
stage.stt |
job.start.stt |
stt workers | new |
stage.nmt |
job.start.nmt |
nmt workers | new |
stage.tts |
job.start.tts |
tts workers | new |
stage.media |
job.start.media |
(not implemented — future) | preprocess stays in backend |
stage.merge |
job.start.merge |
media-service | port 8003 |
orchestrator.dlq |
DLX | manual / alerting | existing |
QoS: every stage queue uses prefetch=1 (one unacked message per consumer). This is the natural backpressure mechanism — slow workers leave messages safely in RabbitMQ instead of in RAM.
Persistence: all messages published DeliveryMode=Persistent (already done in publishNextJob).
The orchestrator uses dynamic stage resolution via stageOrder, nextStage(), and startRoute() in orchestrator/internal/pipeline/manager.go:
var stageOrder = map[string][]db.JobType{
"captionsOnly": {db.JobTypeSTTTranscribe},
"captionsAndTranslation": {db.JobTypeSTTTranscribe, db.JobTypeNMTTranslate},
"translationAndTTS": {db.JobTypeSTTTranscribe, db.JobTypeNMTTranslate, db.JobTypeTTSSynthesize},
"fullDubbing": {db.JobTypeSTTTranscribe, db.JobTypeNMTTranslate, db.JobTypeTTSSynthesize, db.JobTypeDubbingMerge},
}
var startRoute = map[db.JobType]string{
db.JobTypeSTTTranscribe: "job.start.stt",
db.JobTypeNMTTranslate: "job.start.nmt",
db.JobTypeTTSSynthesize: "job.start.tts",
db.JobTypeDubbingMerge: "job.start.merge",
}Three behaviors are implemented:
- Dynamic next-stage resolution (D5).
nextStage(outputType, currentJobType)walksstageOrderfor the parent'soutput_type. - Child-job creation (D7). Before publishing
job.start.X, the orchestrator inserts a childJobrow and publishes that childjob_id. - Cancellation gate (D8). Before advancing, re-read the parent; if
CANCELLED, stop.
output_type → ordered stage list (computed once, walked per result):
output_type |
Stage sequence |
|---|---|
uploadOnly |
media only (no dubbing job created) |
captionsOnly |
STT → done |
captionsAndTranslation |
STT → NMT → done |
translationAndTTS |
STT → NMT → TTS → done |
fullDubbing |
STT → NMT → TTS → merge → done |
Resolution logic (Go, pseudocode):
var stageOrder = map[string][]db.JobType{
"captionsOnly": {JobTypeSTTTranscribe},
"captionsAndTranslation": {JobTypeSTTTranscribe, JobTypeNMTTranslate},
"translationAndTTS": {JobTypeSTTTranscribe, JobTypeNMTTranslate, JobTypeTTSSynthesize},
"fullDubbing": {JobTypeSTTTranscribe, JobTypeNMTTranslate, JobTypeTTSSynthesize, JobTypeDubbingMerge},
}
var startRoute = map[db.JobType]string{
JobTypeSTTTranscribe: "job.start.stt",
JobTypeNMTTranslate: "job.start.nmt",
JobTypeTTSSynthesize: "job.start.tts",
JobTypeDubbingMerge: "job.start.merge",
}
// nextStage returns the stage after `current`, or ("", false) if pipeline is done.
func nextStage(outputType string, current db.JobType) (db.JobType, bool) {
seq := stageOrder[outputType]
for i, s := range seq {
if s == current && i+1 < len(seq) {
return seq[i+1], true
}
}
return "", false
}stateDiagram-v2
[*] --> Received: job.created
Received --> Processing: set parent PROCESSING\ncreate STT child\npublish job.start.stt
Processing --> Advancing: job.results.X (COMPLETED)
Advancing --> CancelCheck: re-read parent
CancelCheck --> Cancelled: parent == CANCELLED
CancelCheck --> NextStage: nextStage exists
CancelCheck --> Completed: no next stage
NextStage --> Processing: create child + publish job.start.next
Processing --> Failed: job.results.X (FAILED)
Completed --> [*]
Failed --> [*]
Cancelled --> [*]
The existing handleNewJob / handleResult / markParentJob / publishNextJob functions in manager.go stay; only handleResult's advancement block is rewritten to: (a) check cancel, (b) resolve next stage from output_type, (c) create child job, (d) publish.
Every Python worker drops BaseJobTask/Celery and becomes a thin AMQP consumer. The inference code is unchanged — only the wrapper changes.
# shared consumer skeleton (per service)
async def on_message(message: aio_pika.IncomingMessage):
payload = json.loads(message.body) # {"job_id": "..."}
job_id = payload["job_id"]
if is_cancelled(job_id): # D8 cooperative cancel
await message.ack()
return
try:
job = load_job(job_id) # read input_data + video_task from DB
mark_processing(job_id)
result = run_stage(job) # existing inference logic
persist_result(job_id, result) # D1 worker writes DB directly
await publish_result(f"job.results.{STAGE}", {
"job_id": job_id, "job_type": JOB_TYPE,
"status": "COMPLETED", "output_data": result.summary,
})
await message.ack()
except Exception as e:
mark_failed(job_id, str(e))
await publish_result(f"job.results.{STAGE}", {
"job_id": job_id, "job_type": JOB_TYPE,
"status": "FAILED", "error": str(e),
})
await message.ack() # ack: failure already reported to orchestratorFailures are reported as a result message (
status: FAILED), not Nack'd. Nack/requeue is reserved for infrastructure faults (DB unreachable, etc.) where a retry could succeed. This avoids infinite redelivery loops on deterministic errors.
The DB helpers (mark_processing, persist_result, mark_failed) are lifted directly from the existing _patch_job / _patch_task in backend/app/jobs/tasks/base.py — reused verbatim, satisfying D1.
The current distributed chord(group(...)) in backend/app/jobs/tasks/nmt.py is removed. The NMT worker reads all STT segments and translates them in-process:
def run_stage(job):
segments = job.video_task.stt_segments
with ThreadPoolExecutor(max_workers=NMT_INTERNAL_CONCURRENCY) as pool:
translated = list(pool.map(translate_one_segment, segments))
# length adjustment (Groq) stays as-is, per segment
return NmtResult(translated_segments=translated,
translated_transcript=join(translated))One job.start.nmt message → one job.results.nmt message. No callback task, no chord bookkeeping.
The Redis completion counter (r.incr(counter_key) in backend/app/jobs/tasks/pipeline.py) is removed. The TTS worker synthesizes every segment and combines, all within one message:
def run_stage(job):
segs = job.video_task.segments # translated segments w/ timing
keys = [synthesize_segment(s) for s in segs] # or bounded pool
combined_key = combine_audio(keys, timing=segs) # existing DubbingMergeService
return TtsResult(combined_audio_key=combined_key, segments=segs)For fullDubbing, audio/video muxing remains a separate merge stage (so it can run on the media service near FFmpeg). For translationAndTTS, TTS is the terminal stage.
NMT/TTS loops should check is_cancelled(job_id) between segments so a long job stops promptly, not just at stage boundaries.
fullDubbing happy path:
sequenceDiagram
participant API as backend
participant MQ as RabbitMQ
participant OR as orchestrator
participant STT as stt
participant NMT as nmt
participant TTS as tts
participant MG as merge
participant DB as PostgreSQL
participant S3 as MinIO
FE->>API: POST /videos/upload (+ output_type)
API->>S3: preprocess: extract audio + thumbnail
API->>DB: update video.audio_path; create parent job + VideoTask
API->>MQ: publish job.created {parent_job_id}
MQ->>OR: job.created
OR->>DB: parent PROCESSING; create STT child
OR->>MQ: job.start.stt {stt_job_id}
MQ->>STT: job.start.stt
STT->>S3: read audio
STT->>DB: write transcript + stt_segments
STT->>MQ: job.results.stt {COMPLETED}
MQ->>OR: job.results.stt
OR->>DB: (cancel check) create NMT child
OR->>MQ: job.start.nmt
MQ->>NMT: job.start.nmt
NMT->>DB: read stt_segments; write translated_segments
NMT->>MQ: job.results.nmt {COMPLETED}
MQ->>OR: job.results.nmt
OR->>MQ: job.start.tts
MQ->>TTS: job.start.tts
TTS->>S3: write per-segment wavs + combined audio
TTS->>DB: write combined_audio_key
TTS->>MQ: job.results.tts {COMPLETED}
MQ->>OR: job.results.tts
OR->>MQ: job.start.merge
MQ->>MG: job.start.merge
MG->>S3: write dubbed video
MG->>DB: write dubbed_video_path
MG->>MQ: job.results.merge {COMPLETED}
MQ->>OR: job.results.merge
OR->>DB: parent COMPLETED (progress 100)
FE->>API: GET /tasks/{id} (poll) -> COMPLETED
Frontend continues to poll GET /api/tasks/{id} and GET /api/jobs/{id} — unchanged from today.
POST /api/jobs/{id}/cancel
-> backend sets parent + active child status = CANCELLED in DB
Orchestrator: on each job.results.* it re-reads the parent;
if CANCELLED -> stop, do not create/publish next stage.
Workers: check is_cancelled(job_id) at stage start and between segments;
if cancelled -> ack and exit without producing output.
No broker-level revocation needed. Worst case, one already-running stage finishes its current segment before noticing the flag.
| Failure type | Handling |
|---|---|
| Deterministic stage error (bad input, model error) | Worker reports status: FAILED; orchestrator marks parent FAILED. No requeue. |
| Transient infra error (DB/S3/broker blip) | Worker Nack(requeue=true) up to max_retries (track via job.retry_count); beyond that, publish FAILED. |
| Worker crash mid-message | Message un-acked → RabbitMQ redelivers to another replica (at-least-once). Idempotent consumer makes reprocessing safe. |
| Poison message (unparseable) | Routed to orchestrator.dlq via DLX for inspection. |
Because delivery is at-least-once, every stage must be safe to run twice on the same job_id:
- DB writes are upserts on the same row (keyed by
job_id/video_task). - S3 keys are deterministic (derived from
job_id+ stage), so re-runs overwrite rather than duplicate.
All services share the existing PostgreSQL and write directly via the lifted _patch_job / _patch_task helpers. Zero schema change. The orchestrator inserts stage child jobs. This is a transitional Shared Database anti-pattern, accepted to maximize migration speed.
flowchart LR
API --> PG[("PostgreSQL")]
ORCH --> PG
STT --> PG
NMT --> PG
TTS --> PG
MEDIA --> PG
Workers stop writing jobs/video_tasks. They return results in messages; the orchestrator becomes the single writer for pipeline state. Backend reads status via DB read-replica or an orchestrator HTTP endpoint. Workers become fully stateless. This removes the dual-writer coupling (and the CeleryTaskID artifact in orchestrator/internal/db/db.go).
Phase 2 (between) is purely deployment: containerize each worker and roll onto Kubernetes with KEDA. No data-model change.
See also: docs/microservices_lld.md — canonical Phase 1/2 LLD.
Incremental Strangler Fig — the monolith keeps running until each queue is cut over.
- Freeze message contracts (§15).
- Extract shared
dablja_worker.pycopies intolibs/dablja-workerinstallable package. -
stt-service: consumer, idempotency, cancel, DB writes, result payload — unit tests passing. -
nmt-service: fan-out, cancel watcher, per-output_typestatus rules — extended unit tests. -
docker-compose.test.ymlcreated;helpers.pyport fixed (5673 → 5672). - E2E scripts:
e2e/test_e2e_captions_only.sh,e2e/test_e2e_captions_and_translation.sh. -
backend-tests.ymlre-enabled;go-tests.ymladded for orchestrator + stt/nmt unit tests. -
docs/microservices_lld.mdwritten with full-app LLD (including Phase 2 TTS/merge specs).
Canonical LLD: docs/microservices_lld.md
- Build
tts-service(port 8005) — extract SilmaTTSModelManager + audio_combine from backend. - Wire
media-servicemerge worker forfullDubbing(orchestrator merge stage restored). - media-service merge production hardening: mux-only path (
combined_audio_key),dablja-worker,/readiness, unit tests + CI, multi-stage Docker. - Orchestrator: restore
JobTypeDubbingMergeinstageOrder["fullDubbing"]. - Pipeline Celery cutover: remove
tts_bridge.py, pipeline Celery TTS tasks, Redis counter from backend. - Prod decommission:
docker-compose.microservices.prod.ymlshipped; Celery/Redis/Flower removed from prod path; standalone TTS via HTTP proxy. - E2E scripts:
translationAndTTS,fullDubbing, cancel mid-TTS, merge-only smoke (e2e/test_e2e_*.sh).
| Environment | Compose file | Pipeline transport |
|---|---|---|
| Local dev | docker-compose.yml |
RabbitMQ + orchestrator + stt/nmt/tts/media-service |
| Production (target) | docker-compose.microservices.prod.yml |
Same — external S3, no Celery/Redis/Flower |
| Production (legacy) | docker-compose.prod.minimal.yml |
Celery + Redis — deprecated; does not run microservices |
# Production microservices stack
docker compose --env-file .env.production -f docker-compose.microservices.prod.yml up -d --buildRequired prod env (in addition to existing secrets): RABBITMQ_URL, RABBITMQ_DEFAULT_USER, RABBITMQ_DEFAULT_PASS. Backend must have RABBITMQ_URL for publish_job_created after media preprocess.
GCP deploy uses .github/workflows/deploy-gcp.yml — switched to docker-compose.microservices.prod.yml.
| Service | Autoscaler | Signal | min/max |
|---|---|---|---|
| backend | HPA | CPU + RPS | 2 / 12 |
| orchestrator | HPA | CPU | 1 / 3 |
| media-service (merge) | KEDA | stage.merge depth |
0 / 4 |
| stt | KEDA | stage.stt depth |
1 / 4 |
| nmt | KEDA | stage.nmt depth |
1 / 6 |
| tts | KEDA | stage.tts depth |
1 / 4 |
| media (preprocess) | — | backend BackgroundTasks | N/A — not a queue worker |
stage.media (future) |
KEDA | stage.media depth |
0 / 8 |
Principles (detail in the scaling discussion already on record):
- KEDA for queue workers (reacts to backlog before CPU spikes); HPA for the stateless API/orchestrator.
- AI workers keep
minReplicaCount: 1(model cold start is minutes); media can scale to zero. - Shared ReadWriteMany PVC for
/model-cacheso replicas don't each re-download models. - GPU workers:
maxReplicaCountmust not exceed GPU inventory (extra pods stayPending). PodDisruptionBudget: minAvailable 1per AI service; topology spread across nodes.
| Risk | Impact | Mitigation |
|---|---|---|
Dual writers on jobs (Phase 1) |
Schema change needs coordinated Go+Python deploy | Keep schema frozen during migration; retire in Phase 3. |
| At-least-once redelivery | Duplicate processing | Idempotent consumers; deterministic S3 keys (§10.3). |
| In-flight cancel latency | Stage finishes before noticing cancel | Per-segment cancel checks in NMT/TTS (§8.4). |
| Lost progress granularity | Coarser than per-segment Celery updates | Orchestrator sets coarse progress per stage; workers may still patch progress mid-stage. |
| Orphaned S3 objects on failure | Storage bloat | Periodic GC sweep keyed by failed/cancelled job_id. |
| Model cold start under load | Slow first response after scale-up | KEDA min=1 + shared model PVC. |
| Big-bang temptation | Risky cutover | Strangler Fig, one queue at a time, validate shortest pipelines first. |
{ "job_id": "<parent FULL_DUBBING_PIPELINE uuid>" }{ "job_id": "<child stage job uuid>" }Workers load all input (S3 keys, params, prior-stage output) from the DB via job_id — Claim Check: no payloads on the wire.
Matches the existing WorkerResultPayload in orchestrator/internal/pipeline/manager.go:
{
"job_id": "<child stage job uuid>",
"job_type": "STT_TRANSCRIBE | NMT_TRANSLATE | TTS_SYNTHESIZE | DUBBING_MERGE",
"status": "COMPLETED | FAILED",
"output_data": { "...": "small summary / keys only" },
"error": "present only when FAILED"
}
output_datacarries only references and small summaries (e.g.combined_audio_key, segment counts) — never raw transcripts/audio. Full results live invideo_tasks/ S3.