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-jobs topic — core, image, gates, sequential — filtered at the Pub/Sub layer by a tier message attribute, each tier its own maxMessages concurrency cap. sequential (ordered delivery, CATEGORY today) is split out from core specifically 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 9 PRODUCT_* services are registered today, dispatched through EntityMigrationServiceFactory.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.ts wraps the call behind ICategoryMigrationRepository, built via the shared createDownstreamApiClient choke point (adds X-Tenant-ID + system-identity X-User-Id/X-Role headers on top of node-lang-core-lib’s createHttpClient). 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 a cockatiel-backed breaker from node-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-tier maxMessages caps below are what actually bounds concurrent downstream request load before anything fails (ADR-00044).
  • Dependency gating — before dispatching, checkDependenciesReady() checks every dependsOn entity 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_errors is audit-only (read by tenant-migration’s paginated errors endpoint, never to drive retry); migration_dead_letters holds the exact original message envelope so tenant-migration’s retryBatch can republish it verbatim. Only MigrationDeadLetterReceiver, consuming the dead-letter topic Pub/Sub itself routes a message to after maxDeliveryAttempts is 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

  • getRecord reads one record’s bytes, never the whole cached file. A storage-reference message carries byteOffset/byteLength locating exactly where its record sits in the cached NDJSON file; readMigrationRecordAt seeks and parses only that slice, instead of re-parsing the entire file per message — this replaced an older recordIndex-based lookup that re-parsed the whole file on every message (O(n²) across a wave). A message missing byteOffset/byteLength alongside payloadLocation fails validation.
  • recordFailureOnce makes failure recording idempotent across redeliveries — without it, MIGRATION_RETRY_ON_FAILURE=true’s default nack-on-failure behavior would duplicate migration_errors docs and over-count failed on every redelivery.
  • This mirrors tenant-migration’s IEntityVerifyProcessor factory pattern applied to the dispatch side instead of the verify side — adding a new entity type never touches MigrationItemReceiver itself.
  • tenant-migration’s verify side also has a registered processor for PRODUCT and all 9 PRODUCT_* 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-migration has an active service block in development/docker-compose.yml today — both are fully commented out, so the pipeline can’t be started via docker compose up in 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’s maxMessages on the single running instance, not adding instances (ADR-00044).

Full module reference: tenant-migration-orchestrator/CLAUDE.md.