ADR-00044 — REST API Dispatch and Tiered Concurrency Over Direct Database Writes for Migration Delivery

By Engineering Team•October 11, 2026•6 min read

Status: Accepted Date: 2026-10-11 Authors: Engineering Team

Context

tenant-migration-orchestrator delivers every migrated record — category, warehouse, package, base product, and all nine PRODUCT_* detail types — into its target microservice (product-catalog, inventory-service, media-access-service). Two implementation questions this raises, both visible directly in the current code:

  1. How does a migrated record actually get written into the target microservice’s data? Every entity type’s repository (repository/category/category-migration.repository.ts, repository/product/product-migration.repository.ts, repository/warehouse/..., repository/product-image/..., and the rest) builds an outbound HTTP client via the shared createDownstreamApiClient choke point and calls that microservice’s own admin REST endpoint (e.g. POST /admin/api/v1/category, POST /admin/api/v1/products/basic-info). None of these repositories holds a database driver for another service’s datastore — the only Mongo clients in this service’s repository layer (repository/batch, repository/id-mapping, repository/migration-error, repository/dead-letter) write to this service’s own collections, never another microservice’s.
  2. How is the rate at which records hit a downstream microservice’s API controlled, regardless of how many records a tenant’s bundle contains? The orchestrator’s four Pub/Sub subscriptions (core/image/gates/sequential) each carry their own maxMessages concurrency cap, enforced per subscription in message-receiver/migration-item.receiver.ts.

Decision Drivers (FRs & NFRs)

  • SR-029 FR-16 — each record is routed to its target microservice’s REST API through a dedicated repository per entity type, never a single hardcoded call.
  • SR-029 FR-17 — every outbound call shares a circuit breaker keyed by destination baseURL.
  • SR-029 NFR-03 — the orchestrator’s four tier-filtered subscriptions each have their own maxMessages concurrency cap, independent of the others.
  • [[00-global-microservice-rules]] / [[02-modularity-and-composition]] — any outbound call to a sibling microservice’s API is wrapped in a repository/<provider>/, the same way a database or gRPC dependency is; service/ never holds a raw HTTP client.

Decision 1 — REST API dispatch vs. direct database writes

Option 1 — Write directly into each target microservice’s own database

The orchestrator would hold a Mongo/Postgres client per target microservice and insert migrated records straight into product-catalog’s, inventory-service’s, or media-access-service’s own collections/tables, bypassing their REST APIs entirely.

Pros:

  • One fewer network hop per record — no outbound HTTP call, no downstream service process in the path at all.
  • No dependency on a target microservice being up or its API contract being stable — only its database schema matters.

Cons:

  • Every piece of business validation and business logic that microservice’s own API layer applies before persisting — required-field checks, cross-entity consistency rules, derived-field computation, the five-field audit contract ([[00-global-microservice-rules]]‘s mandatory tenant_id/created_user_id/updated_user_id/created_at/updated_at columns) — would have to be reimplemented a second time inside the migration pipeline, or skipped entirely. A direct insert has no way to reuse logic that lives inside that service’s own service/domain layers; only its API surface is reusable from outside the process.
  • Two independent write paths into the same data (the microservice’s own API, and the migration pipeline’s direct writes) means any future change to that microservice’s validation rules, derived fields, or schema has to be mirrored in the migration pipeline by hand, with no compiler or test suite in either codebase catching a drift between the two.
  • Couples the migration pipeline to each target microservice’s internal schema (table/collection names, field types, encoding of enums) rather than its public contract — a schema refactor inside product-catalog that doesn’t change its API would still break the migration pipeline.
  • This would also be a direct violation of this monorepo’s own standing rule that any outbound call to a sibling service is wrapped behind a repository/<provider>/ the same as a database dependency is (see Decision Drivers) — the data-store template matrix has no “write directly into another service’s database” pattern anywhere in this monorepo today.

Option 2 — Dispatch via each target microservice’s own REST API (CHOSEN)

Every entity type’s repository calls its target microservice’s existing admin REST endpoint through createDownstreamApiClient, routed per entity type via EntityMigrationServiceFactory.getForType(entityType).

Pros:

  • The target microservice’s own business validation and business logic run exactly once, in exactly the place they already live — the migration pipeline doesn’t need its own copy of (for example) product-catalog’s category-validation rules, because calling POST /admin/api/v1/category runs those rules for free. A migrated record and a record created through the normal admin UI go through the identical validation path.
  • The five-field audit contract ([[00-global-microservice-rules]]) is populated by the target microservice itself, from its own auth-claims extraction, exactly as it would be for any other caller — the migration pipeline only has to send the right X-Tenant-ID/X-User-Id/X-Role headers (via createDownstreamApiClient), not reimplement audit-field population.
  • A target microservice’s internal schema can change freely as long as its public API contract doesn’t — the migration pipeline is coupled to a stable, versioned surface, not internal storage details.
  • Matches this monorepo’s existing “repository per provider, one method per endpoint” doctrine ([[02-modularity-and-composition]]) exactly — this is the same pattern shipment-service’s Shiprocket integration and payment-service’s Razorpay integration already use for third-party APIs, generalized to a sibling-microservice API instead of an external provider’s.

Cons:

  • One more network hop and one more point of failure per record than a direct write — if the target microservice is slow or down, dispatch stalls or fails, whereas a direct database write would only depend on the database itself being reachable.
  • Every target microservice’s admin API must already exist and support the operations migration needs — a microservice with no suitable admin endpoint for a given entity type would need one built before migration could support it, rather than migration being able to write around an API gap.

Decision 2 — Bounding downstream request load, independent of batch size

Option 1 — Single undifferentiated subscription, one shared concurrency knob

All entity types would be published onto one Pub/Sub subscription with a single maxMessages cap, consumed by however many instances of one worker type happen to be running.

Pros:

  • Simplest possible configuration surface — one concurrency number to tune.

Cons:

  • A data shape with very different per-record cost (image upload/processing vs. a lightweight category row) is forced to share the same concurrency budget — a cap high enough for cheap records is too high for expensive ones, and a cap low enough for expensive records under-utilizes capacity for cheap ones. This is exactly the real incident this architecture already avoided elsewhere: the image tier’s low maxMessages cap (2, vs. 10 for core/gates/sequential) exists specifically because an earlier entity-agnostic subscription let roughly 12 concurrent image records overload local image-processing capacity.
  • An ordered entity type (CATEGORY, which requires sequential delivery for parent-reference resolution) sharing a subscription with unordered, high-volume entity types risks head-of-line blocking an unrelated record behind an ordering key — the real 2026-08-07 incident this architecture’s sequential/core split was built to fix.

Option 2 — Four tier-filtered subscriptions, each with an independent maxMessages cap (CHOSEN)

core, image, gates, and sequential are separate Pub/Sub subscriptions on the same migration-jobs topic, filtered by a tier message attribute set at publish time (tierForEntityType), each with its own maxMessages default (core: 10, image: 2, gates: 10, sequential: 10).

Pros:

  • Bounds concurrent in-flight requests to any one downstream destination independently of total batch size — whether a tenant’s bundle contains 10 records or 50,000, at most maxMessages records per tier are ever being dispatched to a downstream microservice’s API at the same instant; Pub/Sub’s own subscription backlog holds the rest until a worker pulls the next message. A larger batch means a longer queue, not a higher instantaneous request rate.
  • Each tier’s cap is tuned to that data shape’s real cost — the image tier’s cap of 2 caps concurrent image-processing load independently of how aggressively core/gates/sequential records are being dispatched in parallel.
  • The cockatiel-backed circuit breaker, keyed by destination baseURL and shared across every entity type calling the same downstream service, is a second, independent safety net on top of the maxMessages caps — but it is reactive, not proactive: it only trips after MIGRATION_CIRCUIT_BREAKER_FAILURE_THRESHOLD (default 5) consecutive failures already occurred, then fails fast for MIGRATION_CIRCUIT_BREAKER_RESET_TIMEOUT_MS (default 30000ms) before probing again. It protects a downstream service from being hammered after it starts failing; the maxMessages caps are what actually bounds request concurrency before anything has failed.
  • The worker (MigrationItemReceiver) is a stateless Pub/Sub puller with no in-memory state tied to a specific message beyond the duration of handling it — structurally compatible with running more than one instance against the same four subscriptions, since Pub/Sub pull subscriptions are inherently a competing-consumers model across any number of subscribers pulling from the same subscription. This is a structural property of the chosen design, not something exercised in this codebase today: development/docker-compose.yml’s tenant-migration-orchestrator block has no replicas:/scaling configuration even when active, and that block is currently fully commented out entirely (TD-00023). Increasing throughput for a very large batch today means raising a tier’s maxMessages env var on the single running instance, not adding instances — horizontal scaling across multiple orchestrator processes is a capability this design doesn’t preclude, not one it has configured or load-tested.

Cons:

  • Four independent caps are more configuration surface than one — a new entity type must be assigned to the correct existing tier (or justify a new one) rather than inheriting a single default.
  • Because horizontal scaling across instances isn’t actually configured anywhere in this monorepo today, the only throughput lever that exists in practice for a very large batch is raising a single instance’s per-tier maxMessages value — which raises concurrent downstream load per worker rather than spreading it across more workers, the opposite trade-off from what multi-instance scaling would offer.

Final Decision

Dispatch every migrated record through its target microservice’s own REST API (Decision 1, Option 2), reusing that microservice’s existing validation, business logic, and audit-field population instead of duplicating it in the migration pipeline — consistent with this monorepo’s standing “repository per provider” doctrine. Bound downstream request load with four tier-filtered Pub/Sub subscriptions, each with an independent maxMessages concurrency cap (Decision 2, Option 2), backed by a reactive circuit breaker as a second line of defense once failures start. The tier caps are what keeps downstream load bounded regardless of whether a tenant’s bundle has 10 records or 50,000 — a larger batch lengthens the Pub/Sub backlog, not the instantaneous request rate. Running multiple orchestrator instances against the same subscriptions is a structurally available scaling path this design doesn’t block, but it is not configured or exercised anywhere in this codebase today — treat any claim that this service “scales horizontally” as describing its architecture’s compatibility with that model, not a deployed or tested capability.