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.ts consumes to create the migration_batches document; there is no POST endpoint 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 an IEntityVerifyProcessor factory, not hardcoded; all 13 known entity types — including PRODUCT and its 9 PRODUCT_* 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 tier Pub/Sub message attribute (core/image/gates/sequential, from tierForEntityType), 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 verify and execute return 202 Accepted immediately — 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) via writeMigrationRecords, 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 with byteOffset/byteLength (where the line sits in the file) instead of a recordIndex — see tenant-migration-orchestrator’s matching readMigrationRecordAt read path. Batches verified before this NDJSON format change carry JSON-array files and recordIndex-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 touches VerifyService/ExecuteService themselves. See tenant-migration-orchestrator’s matching factory.
  • CATEGORY is 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 the sequential tier rather than core.
  • A stale api-e2e-tests/tests/tenant-migration/migration.spec.ts still tests a /migration/start route 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-orchestrator 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).
  • node-lang-core-lib is consumed as a file:../node-lang-core-lib dependency — needs its own one-time npm install plus NODE_OPTIONS=--preserve-symlinks on every start path, or peer-dependency requires fail at boot (not at tsc/build time). See node-lang-core-lib/CLAUDE.md’s known gaps.

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