tenant-migration-orchestrator — Per-Record Migration Dispatch Worker
By Engineering Team•October 10, 2026•6 min read
Responsibility
tenant-migration-orchestrator is the second and final stage of the migration-data pipeline: it has no HTTP controllers and no gRPC surface — every unit of work starts from a Pub/Sub message tenant-migration published, never an inbound request.
- 4-tier Pub/Sub subscription split on the single
migration-jobstopic —core,image,gates,sequential— filtered at the Pub/Sub layer by atiermessage attribute, each tier its ownmaxMessagesconcurrency cap.sequential(ordered delivery,CATEGORYtoday) is split out fromcorespecifically so an ordered entity type’s shared ordering key can never head-of-line-block an unrelated unordered message on the same subscription — a real 2026-08-07 incident this split fixed. - Entity routing via factory, not a hardcoded switch — every entity type implements
IEntityMigrationService;CategoryMigrationService,WarehouseMigrationService,PackageMasterMigrationService, and all 9PRODUCT_*services are registered today, dispatched throughEntityMigrationServiceFactory.getForType(entityType). - Outbound calls are repositories, never a
transport/layer — calling another service’s REST API is treated the same as any other outbound I/O boundary (database, gRPC):repository/category/category-migration.repository.tswraps the call behindICategoryMigrationRepository, built via the sharedcreateDownstreamApiClientchoke point (addsX-Tenant-ID+ system-identityX-User-Id/X-Roleheaders on top ofnode-lang-core-lib’screateHttpClient). See ADR-00044 for why every entity type dispatches via its target microservice’s own REST API rather than a direct database write. - Circuit breaker, keyed by
baseURL— every outbound repository call is wrapped in acockatiel-backed breaker fromnode-lang-core-lib; every entity type calling the same downstream service shares one breaker and failure count, so an outage trips once, not once per entity type. This is a reactive failure-isolation mechanism (it trips only after consecutive failures already happened) — the per-tiermaxMessagescaps below are what actually bounds concurrent downstream request load before anything fails (ADR-00044). - Dependency gating — before dispatching,
checkDependenciesReady()checks everydependsOnentity type has finished its own wave (processed + failed >= queued); a not-ready message is always nacked and redelivered, regardless of the general retry-on-failure config. - Dead-letter queue is the real retry state machine —
migration_errorsis audit-only (read bytenant-migration’s paginated errors endpoint, never to drive retry);migration_dead_lettersholds the exact original message envelope sotenant-migration’sretryBatchcan republish it verbatim. OnlyMigrationDeadLetterReceiver, consuming the dead-letter topic Pub/Sub itself routes a message to aftermaxDeliveryAttemptsis exhausted, ever writes to it.
Tech Stack
| Concern | Choice |
|---|---|
| Language | Node.js (NestJS 10) |
| Data store | MongoDB (migration_batches progress counters, migration_id_mapping, migration_errors, migration_dead_letters) |
| Messaging | Firebase Pub/Sub — 4 tier-filtered subscriptions on migration-jobs, plus a dedicated dead-letter subscription |
| Outbound HTTP | Axios via createDownstreamApiClient (wraps node-lang-core-lib’s createHttpClient + a cockatiel circuit breaker) |
| Storage | NDJSON records on the shared assets mount (large-payload records only), cached once per payloadLocation in local /tmp scratch |
| DI pattern | Symbol-token ports-and-adapters, same convention as tenant-migration |
| Shared logic | node-lang-core-lib — typed errors, logging, withMigrationReceiver (a Pub/Sub-receiver variant requiring entityType/batchId/tenantId/recordId on the envelope) |
Ports
| Gateway | HTTP | gRPC | Service Name |
|---|---|---|---|
None — no Nginx entry, no REST controllers, no authMiddleware |
3000 (env PORT; docker-compose maps 3002:3002) |
None | tenant-migration-orchestrator |
No health endpoint exists today despite the migration-data deployment checklist calling for GET /health — app.listen(port) starts an Express server with zero routes registered, and .env.example’s documented PORT=3000 doesn’t match docker-compose’s (currently commented-out) 3002:3002 mapping; both are pre-existing, unresolved gaps (TD-00023).
Pub/Sub Tiers
| Tier | Entity types | maxMessages default |
|---|---|---|
core |
WAREHOUSE, PACKAGEMASTER, PRODUCT, PRODUCT_SPECIFICATION, PRODUCT_VARIANT, PRODUCT_OPENING_ENTRY, PRODUCT_PRICING, PRODUCT_PACKAGE_MAP, PRODUCT_VOLUMETRIC, PRODUCT_OPENING_ENTRY_PROCESS |
10 |
image |
PRODUCT_IMAGE |
2 (deliberately low — caps concurrent image-processing memory use) |
gates |
PRODUCT_PUBLISH |
10 |
sequential |
Every entity type flagged requiresOrderedDelivery — CATEGORY today |
10 |
Data
| Collection | Purpose |
|---|---|
migration_errors |
Audit-only, one document per failed record — read by tenant-migration’s errors endpoint, never drives retry. |
migration_dead_letters |
The actual retry state machine — the original message envelope for every record that exhausted delivery attempts. Write-only from this service; read/deleted by tenant-migration’s retryBatch via the same physical MongoDB connection. |
migration_id_mapping |
Old-ID → new-ID lookups, shared across entity types (parent-category resolution, etc.). |
Implementation Notes
getRecordreads one record’s bytes, never the whole cached file. A storage-reference message carriesbyteOffset/byteLengthlocating exactly where its record sits in the cached NDJSON file;readMigrationRecordAtseeks and parses only that slice, instead of re-parsing the entire file per message — this replaced an olderrecordIndex-based lookup that re-parsed the whole file on every message (O(n²) across a wave). A message missingbyteOffset/byteLengthalongsidepayloadLocationfails validation.recordFailureOncemakes failure recording idempotent across redeliveries — without it,MIGRATION_RETRY_ON_FAILURE=true’s default nack-on-failure behavior would duplicatemigration_errorsdocs and over-countfailedon every redelivery.- This mirrors
tenant-migration’sIEntityVerifyProcessorfactory pattern applied to the dispatch side instead of the verify side — adding a new entity type never touchesMigrationItemReceiveritself. tenant-migration’s verify side also has a registered processor forPRODUCTand all 9PRODUCT_*detail types today — a prior claim that it didn’t was stale; both sides of the pipeline have full 13-entity-type parity (TD-00023).- No automatic cleanup of the local
/tmp/migrations/<batchId>payload cache — an accepted, bounded gap; this service has no “batch finished” lifecycle event of its own to key cleanup off (TD-00023). - Neither this service nor
tenant-migrationhas an active service block indevelopment/docker-compose.ymltoday — both are fully commented out, so the pipeline can’t be started viadocker compose upin local dev (TD-00023). - This worker is stateless per message and structurally compatible with running multiple instances against the same four subscriptions (Pub/Sub pull subscriptions are inherently a competing-consumers model) — but no
replicas:/scaling configuration exists anywhere for this service today, even inside its commented-out compose block. The only throughput lever that actually exists in this codebase for a large batch is raising a tier’smaxMessageson the single running instance, not adding instances (ADR-00044).
Related Documents
migration-data/CLAUDE.md— architecture spec for the full verify → Pub/Sub → orchestrator pipeline- tenant-migration — publishes the records this service consumes
- ADR-00015 — Node vs. Go for the Migration Pipeline Runtime
- product-catalog — the downstream REST target for CATEGORY and all PRODUCT_* dispatch today
- BRD-028 — Tenant Catalog Bulk Data Migration
- SR-029 — Tenant Catalog Bulk Data Migration Spec
- ADR-00043 — NDJSON Streaming and Wave-Barrier Execution for Tenant Catalog Migration
- ADR-00044 — REST API Dispatch and Tiered Concurrency Over Direct Database Writes for Migration Delivery
- Architecture-00024 — Tenant Catalog Bulk Migration Component Topology and Data Flow
- TD-00023 — Tenant Catalog Bulk Migration Gaps
Full module reference: tenant-migration-orchestrator/CLAUDE.md.