tenant-migration — Bulk Catalog Import: Verify, Execute, Publish
By Engineering Team•October 10, 2026•6 min read
Responsibility
tenant-migration turns a tenant’s uploaded CSV bundle into a verified, wave-ordered stream of per-record Pub/Sub messages that tenant-migration-orchestrator dispatches to each record’s target microservice API.
- Batch creation is event-driven, not a REST call — a tenant’s CSV bundle upload to GCS fires a Storage-trigger envelope that
message-receiver/migration-batch/migration-batch-created.receiver.tsconsumes to create themigration_batchesdocument; there is noPOSTendpoint for starting a batch. See ADR-00045 for why this waits for GCS’s own upload-finalize confirmation rather than a synchronous client call. - Verify (
POST verify/:batchId) — an Agenda job (VerifyService.runVerify→doRunVerify) that extracts the uploaded zip, checks schema presence per entity type, and compiles/validates each entity’s CSV rows into a structured summary — EXTRACT → SCHEMA → COMPILE. Per-entity-type logic is pluggable via anIEntityVerifyProcessorfactory, not hardcoded; all 13 known entity types — includingPRODUCTand its 9PRODUCT_*detail types — have a registered processor today, matching the orchestrator’s dispatch-side coverage one for one. - Execute (
POST execute/:batchId) — a second Agenda job (ExecuteService.runExecute→doExecute) that publishes one wave of records at a time across 4 fixed stage buckets (stage_1_foundational→stage_2_dependent→stage_3_publish→stage_4_finalize), blocking on a wave barrier (waitForWave) before advancing — never a per-entity dependency graph walked at publish time. - Outbound tier tagging — every published record carries a
tierPub/Sub message attribute (core/image/gates/sequential, fromtierForEntityType), which is what lets the orchestrator route by attribute filter instead of inspecting payload content. - Batch lifecycle — list/get/delete/cancel/retry, all tenant-isolated via
findOwnedBatch(batchId, tenantId)(404s identically whether the batch doesn’t exist or belongs to another tenant), plus an SSE polling stream for live batch-status updates. - Both
verifyandexecutereturn202 Acceptedimmediately — the actual work runs as an Agenda job, never blocking the HTTP request/response cycle.
Tech Stack
| Concern | Choice |
|---|---|
| Language | Node.js (NestJS 10) |
| Data store | MongoDB (migration_batches) |
| Messaging | Firebase Pub/Sub — inbound (Storage-upload trigger envelope), outbound (migration-item publisher, one message per record, tier-tagged) |
| Storage | GCS — raw zip archive via IMigrationStorageService; processed intermediate artifacts are NDJSON on a shared assets mount (not GCS, not a JSON array) |
| Job scheduling | Agenda (MongoDB-backed), verify/execute as background jobs |
| DI pattern | Symbol-token ports-and-adapters (Symbol('IThing') + { provide, useClass }), never class/string tokens |
| Shared logic | node-lang-core-lib — typed errors, logging, AsyncLocalStorage request context, auth middleware |
| Template | Predates @templates/node-mongo-microservice — is that template’s own source pattern, not scaffolded from it |
Ports
| Gateway | HTTP | gRPC | Service Name |
|---|---|---|---|
8000 (Nginx /migration/*, auth_request /_auth_verify on every route including health) |
3001 (env PORT) |
None | tenant-migration |
API Endpoints
| Method | Path | Purpose |
|---|---|---|
POST |
/migration/verify/:batchId |
Enqueue the verify Agenda job — 202 Accepted |
POST |
/migration/execute/:batchId |
Enqueue the execute Agenda job (wave-barrier gated publish) — 202 Accepted |
GET |
/migration/batches |
List the caller’s tenant-scoped batches |
GET |
/migration/batches/:batchId |
Get one batch’s current status/summary |
DELETE |
/migration/batches/:batchId |
Delete a batch, including its GCS artifacts and local scratch directory |
POST |
/migration/batches/:batchId/cancel |
Cancel an in-flight verify/execute Agenda job |
POST |
/migration/batches/:batchId/retry |
Re-publish failed records for an EXECUTION_FAILED batch |
GET |
/migration/batches/:batchId/errors |
Paginated per-record error list (reads the audit-only migration_errors collection) |
GET (SSE) |
/migration/stream/:batchId |
Live batch-status polling stream |
GET |
/migration/health |
Health check (still behind auth_request /_auth_verify — no bypass) |
Data
| Collection | Purpose |
|---|---|
migration_batches |
One document per upload — verification summary per entity type, the 4-stage execute plan, per-stage queued/processed/failed counters, terminal status (VERIFIED, VERIFICATION_FAILED, EXECUTION_FAILED, CANCELLED, …). |
migration_order |
DEFAULT_ORDER — the single source of truth mapping each entity type to its stage number. |
migration_errors (audit-only) and migration_dead_letters (the real retry state machine) are owned and written by tenant-migration-orchestrator; this service only reads them (errors list, retry re-publish) against the same physical MongoDB connection.
Implementation Notes
- Nothing in the verify pipeline buffers a whole file in memory. The staging zip is streamed straight to a local scratch file (
SCRATCH_ROOT/<batchId>.zip) rather than downloaded as a buffer; from that local file, the raw-archive upload to the primary bucket and the zip extraction run concurrently (Promise.allSettled), both reading off disk. Each processor’s compiled output is written as NDJSON (one record per line) viawriteMigrationRecords, streamed to disk rather than built as one big JSON string/array. Execute-time publishing reads that NDJSON one line at a time and tags large-record messages withbyteOffset/byteLength(where the line sits in the file) instead of arecordIndex— see tenant-migration-orchestrator’s matchingreadMigrationRecordAtread path. Batches verified before this NDJSON format change carry JSON-array files andrecordIndex-based messages and must be re-verified before they can be executed — no compatibility shim exists (TD-00023). - Entity-type extensibility is a factory pattern on both the verify side (
IEntityVerifyProcessor) and — on the orchestrator side — the dispatch side; adding a new entity type never touchesVerifyService/ExecuteServicethemselves. See tenant-migration-orchestrator’s matching factory. CATEGORYis the only entity type published with Pub/Sub ordering enabled (requiresOrderedDelivery) today, since it’s the only one that self-references (parent-category resolution needs prior records’ new IDs already mapped) — routed onto thesequentialtier rather thancore.- A stale
api-e2e-tests/tests/tenant-migration/migration.spec.tsstill tests a/migration/startroute and a direct multipart upload to/migration/verify— neither exists in the current controller; not yet fixed (TD-00023). - Neither this service nor
tenant-migration-orchestratorhas 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). node-lang-core-libis consumed as afile:../node-lang-core-libdependency — needs its own one-timenpm installplusNODE_OPTIONS=--preserve-symlinkson every start path, or peer-dependency requires fail at boot (not attsc/build time). Seenode-lang-core-lib/CLAUDE.md’s known gaps.
Related Documents
migration-data/CLAUDE.md— architecture spec for the full verify → Pub/Sub → orchestrator pipeline- tenant-migration-orchestrator — consumes this service’s published records
- ADR-00015 — Node vs. Go for the Migration Pipeline Runtime
- firebase-function — fires the Storage-upload trigger envelope this service’s
message-receiverconsumes - 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
- ADR-00045 — Event-Driven Batch Creation From Storage-Upload Completion
- Architecture-00024 — Tenant Catalog Bulk Migration Component Topology and Data Flow
- TD-00023 — Tenant Catalog Bulk Migration Gaps
Full module reference: tenant-migration/CLAUDE.md.