Nano Store - Ecommerce Docs
Developer ResourcesInventory

Inventory Backend Documentation

Backend architecture, data model, services, cache, queues, runtime rules, and operational behavior for the Inventory module.

Inventory - Backend Documentation

1. Documentation Evidence

AreaFiles InspectedVerified Details
Module wiringinventory.module.ts, inventory-admin-aggregate.module.ts, inventory-import-export.module.ts, inventory-worker.module.ts, inventory-shared.module.tsComposition, shared services
Controllersadmin/stock/*.controller.ts, admin/job/*.controller.tsRoute ownership, guards, permissions
Servicesinventory-write.service.ts, inventory-reservation.service.ts, inventory-availability.service.ts, inventory-ledger.service.ts, inventory-projection.service.ts, inventory-job-lifecycle.service.tsGuarded UPDATEs, lifecycle, projections
DTOsdto/*.ts under each leafValidation
Schemapackages/db/src/schema/inventory/*.tsFour tables, GENERATED columns, CHECKs
Jobspackages/jobs/src/index.ts, workers/*InventoryJob names, lease claim, scheduler
Cachecache-invalidation.tags.ts, cache-invalidation.service.tsinventory domain; triggerForWrite and clearForWrite
Storefront clearinventory-ledger.service.ts, inventory-write.service.ts, workers/inventory-storefront-cache.processor.ts, shared/inventory.constants.ts, services/bullmq/bull.module.ts, config/env.validation.ts, packages/jobs/src/index.tsPer-transaction outbox row, dedicated queue, coalescing, retry options
Mathapps/api/src/utils/inventory/inventory-math.util.tsPure arithmetic, projections

2. Backend Scope and Boundaries

Owns

  • Stock counters, reservations, the movement ledger, per-product configuration.
  • Admin surface (stock, configuration, movements, bulk adjust) and import/export jobs.
  • The INVENTORY queue (one worker, five job names) and the maintenance scheduler.
  • product.stock_status as a synchronous projection of the inventory row.

Does Not Own

  • Pricing, promotions, orders, payments — it has no opinion on what a reservation is for.
  • The product domain — it consumes product ids, never the other way.
  • The outbox — generic infra; all enqueues go through it.

Source of Truth

ConcernSource of TruthNotes
Runtime statePostgreSQL (inventory, inventory_reservation, inventory_movement, inventory_job)
AvailabilityGENERATED columns — cannot be written
Movement historyinventory_movement (same-tx)Mongo is analytics only
Job stateinventory_job row + lease claim

3. Module Composition

ModuleTypePathControllersProvidersExportsResponsibility
InventoryModuleAggregateinventory.module.tsNone—LeavesComposes admin/worker/import-export
InventoryAdminAggregateModuleAggregateadmin/None—LeavesComposes stock + job leaves
InventoryStockAdminModuleLeafadmin/stock/InventoryStockAdminController, InventoryStockAdminBulkControllerServices—Stock surface
InventoryJobAdminModuleLeafadmin/job/InventoryJobAdminControllerService—Jobs surface
InventoryImportExportModuleLeafimport-export/NoneServices—Import/export orchestration
InventoryWorkerModuleLeafworkers/NoneProcessor/handlers—Queue + scheduler
InventorySharedModuleLeafshared/NoneWrite/Reservation/Ledger/Availability/ProjectionServicesShared domain services

4. File and Directory Map

apps/api/src/modules/inventory/
  inventory.module.ts
  admin/
    stock/   inventory-stock-admin.{controller,service}.ts
             inventory-stock-admin-bulk.{controller,service}.ts  dto/
             inventory-stock-movements-admin.service.ts   # the ledger read
             inventory-admin-cursor.builder.ts            # keyset on variant_id
    job/     inventory-job-admin.{controller,service}.ts  dto/
  import-export/
    inventory-import-parser.ts   inventory-import-row.ts
    inventory-import.service.ts  inventory-export.service.ts
    inventory-job-lifecycle.service.ts
  shared/
    inventory-write.service.ts       # the ONLY permitted writer
    inventory-reservation.service.ts
    inventory-ledger.service.ts
    inventory-availability.service.ts
    inventory-projection.service.ts
    inventory-filter.builder.ts      inventory-response.builder.ts
    inventory-mutation.types.ts      inventory.constants.ts
  workers/
    inventory-queue.processor.ts     # THE one @Processor
    inventory-{reservation-sweep,reconcile,projection,job}.processor.ts
    inventory-maintenance.scheduler.ts
    inventory-storefront-cache.processor.ts   # THE one @Processor on inventory_storefront_cache
    inventory-storefront-cache.constants.ts   # worker concurrency (1)
packages/db/src/schema/inventory/
  inventory.ts  inventory-reservation.ts  inventory-movement.ts
  inventory-job.ts  enums.ts
apps/api/src/utils/inventory/inventory-math.util.ts   # pure arithmetic

Key files:

FilePurposeKey ExportsNotes
shared/inventory-write.service.tsThe only writer of counter/config columnsInventoryWriteServiceGuarded UPDATEs, variant_id ordering
shared/inventory-variant-resolver.service.tsThe product → variant bridgeresolveStockVariant, resolveDefaultVariantId(s)For callers that hold only a product. Returns null rather than throwing — "every product has one live default variant" is enforced by application layers, not by a constraint, so its absence is representable
shared/inventory-reservation.service.tsReservation lifecycleInventoryReservationServiceGlobal key, guarded transitions
workers/inventory-queue.processor.tsThe one @Processor on INVENTORYInventoryQueueProcessorRoutes via Record<InventoryJob, handler>
import-export/inventory-job-lifecycle.service.tsJob row transitionsclaim, completeExport, failExportZero-row guard
utils/inventory/inventory-math.util.tsPure stock arithmeticderiveStockStatus, stockStatusTransitioned, canReserve, canDisableOversellNo NestJS imports
shared/inventory-ledger.service.tsMovement rows and the storefront-stale outbox rowInventoryLedgerService.record, markStorefrontStaleConstructor holds OutboxService only
shared/inventory.constants.tsStorefront clear constantsINVENTORY_STOREFRONT_CLEARED_FROM_KEY, INVENTORY_STOREFRONT_CLOCK_SKEW_MS (1000), INVENTORY_STOREFRONT_MIN_CLEAR_INTERVAL_MS (2000), INVENTORY_STOREFRONT_STALE_AGGREGATE_ID ("storefront")Key lives under inventory:, which the inventory cache domain never matches
workers/inventory-storefront-cache.processor.tsCoalesced storefront cache clearInventoryStorefrontCacheProcessorCalls CacheInvalidationService.clearForWrite

5. Data Model

5.1 Schema Source

packages/db/src/schema/inventory/
  inventory.ts  inventory-reservation.ts  inventory-movement.ts
  inventory-job.ts  enums.ts

5.2 Tables

inventory

ColumnTypeNullableDefaultIndex/ConstraintRelationNotes
variant_idintegerNo—PKproduct_variant.idOne row per variant — a second row for one variant is unrepresentable. This was product_id until migration 0021: once a product sells in several configurations, stock is a property of the configuration, and a product-keyed row cannot represent it at all
product_idintegerNo—FK, index, not uniqueproducts.idDenormalised from product_variant.product_id and RETAINED after the PK move, because the storefront's hottest read is WHERE product_id IN (...) and joining through product_variant per card would be a wasted hop. A product-keyed query now matches N rows
public_iduuidNouuid7unique—The stock row's own identity, distinct from both ids above
total_quantityintegerNo0CHECKs—Negative legal under allow_oversell (units owed)
reserved_quantityintegerNo0CHECK >= 0—
available_quantityintegerNogenerated——GENERATED ALWAYS AS (total - reserved) — write attempt raises 428C9
stock_statusenumNogeneratedpartial index WHERE stock_status = 'low_stock'—GENERATED CASE over counters
track_inventorybooleanNotrue——Counters are authoritative unless turned off
allow_oversellbooleanNofalse——
low_stock_thresholdintegerNo5CHECK >= 0—Zero means "never warn"
versionintegerNo1CHECK >= 1—Optimistic lock, configuration fields only

Every sort index is (sort_column, variant_id), not (sort_column, product_id). The admin list is keyset-paginated, and a keyset tiebreaker must be unique; product_id stopped being unique at the PK move, and a non-unique tiebreaker makes a page silently skip or repeat rows.

CHECKs: chk_*_total_quantity_* and chk_*_reserved_le_total gated on allow_oversell OR NOT track_inventory.

Every application-side guard that mirrors those CHECKs must carry BOTH escapes. The adjustStock WHERE clause and its util twin validateAdjustment carried only allow_oversell, which made them stricter than the database they mirror — and the gap was reachable, not theoretical.

createForVariant creates every row untracked, and the reserve guard short-circuits on untracked ("tracking disabled means unlimited purchasing, stock ignored"), so an untracked row legitimately reaches reserved > total. Adding stock to such a row was then refused as INVENTORY_INSUFFICIENT_STOCK — an operator receiving 500 units told there was not enough stock, to add stock — and the only delta the guard would accept was larger than the quantity that had actually arrived. The database would have taken the write.

The tell that it was an oversight rather than a decision: the same NOT track_inventory escape had been deliberately added to canDisableOversell and canEnableTracking, with a long comment explaining why. It was applied to two of the three sibling predicates and missed on the third plus its SQL twin.

inventory_reservation

reservation_key varchar globally unique, NOT partial; status enum (active/released/finalized/expired); expires_at business timestamp; quantity positive.

inventory_movement

Append-only ledger, keyed on variant_id (FK to inventory.variant_id) with product_id carried alongside so a product-level audit needs no join: kind enum (6 values incl. correction), reason, source, the signed total_delta / reserved_delta, the post-write total_after / reserved_after snapshots, note, actor_*, correlation_id, timestamps. Written in the same transaction as the counter change.

inventory_job

Mirrors catalog_job: kind (import/export), entity (inventory), status enum, counters, retained errors (cap 500), result_file_url required on completed export.

5.3 Relationship Diagram

6. Services and Responsibilities

6.1 InventoryWriteService

MethodCalled ByReadsWritesSide EffectsErrors
createForProduct()product create/import—inventory row (untracked)——
adjust()admin adjust, importrowcounters + movementprojection (outbox), cacheINVENTORY_ADJUSTMENT_WOULD_GO_NEGATIVE, INVENTORY_INSUFFICIENT_STOCK
updateConfiguration()admin configrow + versionconfig fields (+ movement if counters change)projection, cacheINVENTORY_VERSION_CONFLICT, INVENTORY_OVERSELL_DISABLE_BLOCKED
bulkAdjust()admin bulkrowscounters + movementsprojection, cacheper-item failures

Every mutation is a guarded UPDATE, never a read-then-write — rowCount = 0 means "refused" and is the only trustworthy way to learn there is not enough stock. Multi-row operations sort by variant_id ascending (unordered writes deadlock — reproduced 40P01). The ordering key follows the primary key: ordering by product_id leaves the lock order between two variants of one product unconstrained, which is all a deadlock needs.

6.2 InventoryReservationService

Reserve (idempotent insert under the global key, TTL default 15 min), release (idempotent, twice OK), finalize (409 on second), expire (sweep claims batches). Every transition writes a movement in the same transaction.

6.3 InventoryLedgerService / InventoryAvailabilityService

Ledger: movement writes + reads with _before/_after snapshots. Availability: batched reads for product responses (one query per page).

6.4 InventoryProjectionService

Writes product.stock_status as a synchronous projection: only when tracking is on and the current value is not pre_order (a pre-order product's status is admin truth and is never overwritten). Documented reset on the true → false tracking edge. Mongo activity projection happens asynchronously via the outbox (PROJECT_ACTIVITY).

The status written is the product's AGGREGATE across its live variants, not the status of the one variant that moved. The projection re-reads every inventory row belonging to an active, non-deleted variant of the product and collapses them with aggregateAvailability, the same function and the same PRODUCT_STOCK_STATUS_PRECEDENCE the read path uses — a product is as buyable as its most buyable variant.

This is the correction to a real defect, not a description of a design choice.

The projection used to write the moved variant's own status straight onto the product. Once a product could have more than one variant that was wrong in the most visible way possible: reserving the last unit of a one-unit configuration marked the whole product out_of_stock while a sibling still had ten sellable units, and nothing re-projected until an unrelated movement happened to land on that sibling. The storefront filters on this column, so the product simply disappeared from sale.

The rule already existed — inventory-math.util.ts had written aggregateAvailability precisely because "every caller that still builds a Map keyed on product_id silently keeps whichever row the planner returned LAST". The read path used it. Only this write did not, so the denormalized column and the live-computed answer disagreed for every multi-variant product.

It survived because every fixture in inventory-write.service.spec.ts built exactly one variant per product, which makes "this variant's status == the product's status" true trivially. inventory-stock-admin.int.spec.ts states that lesson in its own header — "a single-variant fixture reproduces none of them" — and it had been applied there and not here.

The trackingTurnedOff edge now also asks the aggregate: it resets to in_stock only when no live variant tracks any more, so "tracking disabled means unlimited purchasing" is true of the product as a whole rather than of one configuration.

Soft-deleted and inactive variants are excluded, matching InventoryAvailabilityService. A retired configuration must not decide whether the product can be bought.

6.5 InventoryLedgerService.markStorefrontStale

MethodCalled ByReadsWritesSide EffectsErrors
markStorefrontStale(executor, { productPublicId, cause, correlationId? })InventoryWriteService (adjustStock, applyReservationDelta, updateConfiguration, applyCorrection)pg_current_xact_id() and now() of the caller's transactionOne outbox_events row (INSERT ... ON CONFLICT DO NOTHING)The dispatcher relays the row to the inventory_storefront_cache queue after commitSYS_INTERNAL_ERROR if the key query returns no row (should not happen)

How it works (inventory-ledger.service.ts:173-207):

  1. One statement reads the transaction key: 'tx_' || pg_current_xact_id() || '_' || <transaction start time in microseconds>. The key matches ^tx_[0-9]+_[0-9]+$ and contains no :, which BullMQ job ids reject.
  2. OutboxService.enqueue writes the row with aggregateType: "inventory", the constant aggregateId "storefront", eventType: "inventory.storefront_stale", jobName: InventoryStorefrontCacheJob.CLEAR, and the transaction key as dedupeKey.
  3. The outbox unique key is (aggregate_type, aggregate_id, job_name, dedupe_key) and the insert does nothing on conflict, so every later call in the same transaction is a no-op: one row per transaction. A 5,000-row import pays one SELECT and one INSERT per row but leaves one row.
  4. The payload (packages/jobs/src/index.ts:1041-1048) is { productPublicId, cause, txKey, correlationId? }. It describes the first visible change in the transaction and is audit data, not routing: the clear is global.

The key contains a clock on purpose, which is an exception to the usual "a dedupe key is never a clock" rule. A retried request is a new transaction whose predecessor row rolled back with it, so a fresh key is correct. Inside one transaction both values are stable. The key holds no integer domain id.

The class only INSERTs. It never UPDATEs inventory, so the single-writer rule is untouched. The constructor is unchanged, so no construction site of the ledger or the writer changed.

6.6 InventoryStorefrontCacheProcessor

The only @Processor on QueueName.INVENTORY_STOREFRONT_CACHE, with concurrency 1 (inventory-storefront-cache.constants.ts:7). It is provided in InventoryWorkerModule. Any job name other than inventory_storefront_cache.clear throws UnrecoverableError.

MethodCalled ByReadsWritesSide EffectsErrors
clear(job)processRedis stamp inventory:storefront:cleared_fromThe same stamp (after a successful clear only)CacheInvalidationService.clearForWrite({ domain: "inventory" })Throws CACHE_REVALIDATION_FAILED when a Redis pattern failed to delete
onFailed(job, error)BullMQ failed eventawait job.isFailed()NoneERROR log on final failure, WARN on retryNone

clear runs these steps (inventory-storefront-cache.processor.ts:127-208). T is job.timestamp, the time the dispatcher added the job, which is after the commit.

  1. Read the stamp. A Redis read error is logged at WARN and treated as "no stamp", so the job clears anyway. A stamp dated more than the clock skew in the future is ignored with a WARN.
  2. Covered: skip. If stamp - 1000 ms > T, a clear began after this job existed, so the job returns (DEBUG [skip]).
  3. Trailing wait. Otherwise, if a stamp exists, the job sleeps until stamp + 2000 ms (never longer than 2000 ms). This job is the trailing clear for everything that arrived since the last clear began. Jobs queued behind it start after it and find themselves covered.
  4. Clear. Capture start = Date.now(), then call clearForWrite({ domain: "inventory", entityId: productPublicId, reason: "inventory_<cause>" }).
  5. Fail loudly. If redisPatternsFailed is not empty, throw with errorCode: CACHE_REVALIDATION_FAILED. The stamp is not written, so BullMQ's retry and every later job still clear.
  6. Stamp after success. Write start to the stamp key with CACHE_TTL.VOLATILE (30 s). A failed write is a WARN, not a throw: a missing stamp only causes one extra clear.
  7. Log [success] inventory_storefront_cache.clear jobId=... txKey=... cause=... waitedMs=... revalidation=....

Properties: at most one wipe per 2 s per worker, and the last change is never dropped, because every job either is covered by a clear that began more than the skew after it existed or performs a clear itself. A crash before step 6 leaves the stamp untouched, so a re-run clears.

6.7 CacheInvalidationService: triggerForWrite vs clearForWrite

Both build the same payload from the registry in cache-invalidation.tags.ts (buildWritePayload). They differ in what they do with failure.

triggerForWrite(params)clearForWrite(params)
Sourcecache-invalidation.service.ts:111cache-invalidation.service.ts:125
ReturnsPromise<void>Promise<CacheWriteClearOutcome>
Redis pattern failureLogged, swallowedReturned in redisPatternsFailed
Unexpected throwSwallowed by revalidateWriteHookPropagates to the caller
Next.js revalidation failureMaintenance-queue retrySame retry, reported as revalidationRetryQueued
Use fromRequest paths (the mutation already committed and must not 5xx)Queue handlers that can throw and be retried

CacheWriteClearOutcome is { redisPatternsFailed: string[]; revalidationReason: string; revalidationRetryQueued: boolean }. redisPatternsFailed is the requested, de-duplicated patterns minus the ones reported deleted.

Contract for future callers. Request handlers keep calling triggerForWrite: its fire-and-forget behaviour is relied on by every existing caller and is locked by a regression test. Call clearForWrite only from a queue handler that throws on a non-empty redisPatternsFailed. It is a separate method rather than a flag, so no existing call site changed.

7. Runtime Flows

7.1 Guarded adjustment

7.2 Reservation reserve

7.3 Storefront stock cache clear

The problem. The storefront caches stock in the product card (inventory.stockStatus, available) and in variant availability, under product:v2:* and catalog:search:*. The writer used to leave invalidation to every caller, and retail cancellation and return-inspection restocks (and checkout reserve and release) never invalidated. A restock left the storefront showing "out of stock" until the 300 s cache TTL ran out.

The mechanism. The writer now records the need to clear inside the same transaction as the stock change. Callers have nothing left to remember.

StepCode PathBehaviorFailure Case
1InventoryWriteService (inventory-write.service.ts:250,328,425,545)Calls markStorefrontStale after the guarded UPDATE returned a row, never when it returned null.Rollback discards the row.
2InventoryLedgerService.markStorefrontStaleOne outbox row per transaction.Outbox insert error aborts the caller's transaction.
3Outbox dispatcherRelays the row to the dedicated queue after commit.A relay failure retries; after 3 attempts the row is dead (see 16.8).
4InventoryStorefrontCacheProcessor.clearCoalesces, then calls clearForWrite.A Redis pattern failure throws, and BullMQ retries.
5BullMQ options5 attempts, exponential backoff from 1000 ms.Final failure stays in the failed set with an ERROR log.

Which writes emit.

Writer methodEmits whencause
adjustStockAlways, after a successful guarded UPDATEadjustment
applyCorrectionOnly when a movement row was recorded (not on the zero-delta early return)correction
updateConfigurationAlways on success, including a body that carries only versionconfiguration
applyReservationDelta (reserve, release, expire, finalize)Only if stockStatusTransitioned(row, delta) is truethe movement kind

stockStatusTransitioned(after, delta) (utils/inventory/inventory-math.util.ts, stockStatusTransitioned) rebuilds the before-state by subtracting the deltas from the RETURNING row and compares deriveStockStatus before and after. That is exact because the UPDATE is relative and atomic under the row lock, and this path writes no configuration column. Product status is the highest-precedence member of its variants' statuses, so a product card can change only if some variant crossed a band.

  • A reserve inside a band (for example in_stock to in_stock) emits nothing.
  • Finalize never emits. It moves total and reserved together, so available is unchanged.
  • A status that flips and flips back inside one transaction emits one row, because of the per-transaction collapse. That can over-clear but never under-clears.
  • An inactive or soft-deleted variant may emit although the storefront ignores it. That over-clears and is harmless.
  • createForVariant does not emit. It inserts an untracked zero-count row, which cannot affect purchasability.
  • The exact reserve and release counts on the storefront lag until the next crossing. The cached available is exact only at a band crossing or a total or configuration change.

Which other triggers remain. Five request-path triggerForWrite calls remain as a latency optimisation, because they clear immediately instead of waiting for the outbox: inventory-stock-admin.service.ts (two: the configuration update and the stock adjust), inventory-stock-admin-bulk.service.ts (bulk adjust), pos/shared/pos-sale-completion.service.ts (sale completion, POS_CACHE_DOMAIN) and pos/shared/pos-counter-return.service.ts (fresh counter returns). The double clear on those paths is harmless. Three worker-side triggers were removed because the writer now covers them through the queue: stock import (inventory-import.service.ts), the reservation sweep (inventory-reservation-sweep.processor.ts) and the reconcile correction (inventory-reconcile.processor.ts). Their clears arrive through inventory_storefront_cache after the outbox tick instead of at the end of the worker.

Lag bound. Retail cancellation and return inspection clear asynchronously, so the storefront can show stale stock for about 5 s after commit (owner-approved, no synchronous clear):

ComponentBound
Wait for the next outbox tickup to 5 s (OUTBOX_DISPATCH_INTERVAL_MS)
Outbox backlog ahead of the row100 rows per 5 s pass by default (OUTBOX_DISPATCH_BATCH_SIZE, configurable up to 500)
Coalescing waitup to 2 s
Clear durationthe Redis pattern deletes

The outbox dispatches oldest first across all queues. A 5,000-row stock import writes 5,000 PROJECT_ACTIVITY rows, so a cancel committed right after it waits about 250 s at the default batch size, as every other outbox consumer does. Raising OUTBOX_DISPATCH_BATCH_SIZE to 500 cuts that to about 50 s.

8. Cache

Cache Key PatternBuilderValueTTLInvalidationCaller
product:v2:* (product cards, variant availability)the products modulecached product reads carrying stockexisting (CACHE_TTL.STANDARD, 300 s)inventory domain clearInventoryStorefrontCacheProcessor through clearForWrite; the request-path triggers in 7.3 through triggerForWrite
catalog:search:*the catalog modulesearch results carrying stock statusexistingsamesame
inventory:storefront:cleared_fromCacheKeyUtil.build(INVENTORY_CACHE_PREFIX, [["storefront","cleared_from"]])epoch ms: start time of the last successful clearCACHE_TTL.VOLATILE (30 s)Overwritten after each successful clearInventoryStorefrontCacheProcessor

The inventory domain (cache-invalidation.tags.ts:284-307) clears the storefront tags plus the two Redis patterns above. The stamp key sits under inventory:, which neither pattern matches, so a clear never deletes it.

  • Who clears: the writer's per-transaction outbox row (see 7.3), plus the five request-path triggers. Product responses carrying the inventory group are refreshed the same way.
  • The wipe is global. Cache keys are not per product, so entityId is carried for logs and audit only. Per-product keys are a follow-up.
  • Failure handling: a Redis pattern failure throws and BullMQ retries (5 attempts). A Next.js revalidation failure is not a job failure: it keeps the maintenance-queue retry. If every retry fails, staleness is bounded by the 300 s TTL.

9. Jobs and Workers

QueueDispatcherJob names
INVENTORYinventory-queue.processor.ts (the only @Processor)IMPORT_STOCK, EXPORT_STOCK, SWEEP_EXPIRED_RESERVATIONS, RECONCILE, PROJECT_ACTIVITY
INVENTORY_STOREFRONT_CACHE (inventory_storefront_cache)inventory-storefront-cache.processor.ts (the only @Processor, concurrency 1)inventory_storefront_cache.clear (InventoryStorefrontCacheJob.CLEAR)

INVENTORY_STOREFRONT_CACHE is its own queue so an import, export or activity backlog on INVENTORY cannot delay a clear. It is in REGISTERED_QUEUES (bull.module.ts), which is the only way a queue fed solely by the outbox dispatcher (it passes only jobId) gets env-configured retry options, and it also puts the queue on bull-board.

OptionDefaultEnv key
attempts5BULL_QUEUE_INVENTORY_STOREFRONT_CACHE_ATTEMPTS
backoffexponential, 1000 ms (about 15 s of retries)BULL_QUEUE_INVENTORY_STOREFRONT_CACHE_BACKOFF_DELAY_MS
removeOnComplete count1000BULL_QUEUE_INVENTORY_STOREFRONT_CACHE_REMOVE_ON_COMPLETE_COUNT
removeOnComplete ageinherited, 7200 sBULL_DEFAULT_REMOVE_ON_COMPLETE_AGE_SEC
removeOnFail age and countinherited, 172800 s and 5000BULL_DEFAULT_REMOVE_ON_FAIL_AGE_SEC, BULL_DEFAULT_REMOVE_ON_FAIL_COUNT

The three queue-specific keys are declared in config/env.validation.ts (BULL_QUEUE_INVENTORY_STOREFRONT_CACHE_*). The jobId is outbox_<id>_<ms>, set by the dispatcher. The payload is InventoryStorefrontStalePayload (see 6.5).

Final failure is decided from job state. onFailed awaits job.isFailed() rather than comparing attemptsMade with attempts, so a stall-limit or UnrecoverableError failure that has attempts left is still reported as final. onFailed falls back to the attempt count only if the state read itself fails.

  • Import/export: enqueued through the outbox; lease-based claim guarded on status = 'queued'; import owns its terminal write (accumulates per-row errors); export's terminal write carries total_rows + result_file_url together; failExport never advertises a partial file.
  • Sweep: every minute via @Cron — settles expired reservations in batches (default TTL 15 min).
  • Reconcile: every hour — asserts reserved = SUM(active) and the newest _after matches counters; repairs with correction movements, never silent rewrites; heals products with no row.

9.1 How the reconciler picks its batch, and why that is load-bearing

It reads a bounded batch per pass (INVENTORY_RECONCILE_BATCH_SIZE), ordered last_reconciled_at ASC NULLS FIRST, variant_id. Every row it examines is stamped — clean ones too — so a row just audited sorts last and cannot come up again until every other row has had a turn. Never-audited rows go first, which is why the column is nullable with no backfill.

This job is the only drift detection the module has, and its coverage was a fixed prefix of the table.

The claim was ORDER BY product_id LIMIT n with no cursor, offset or watermark, so every hourly pass examined the same first n rows. Past n inventory rows the remainder was never audited — not "within a day" as the constant's comment claimed, but never. product_id also stopped being unique at migration 0021, so the prefix was not even deterministic across passes.

Separately, the per-row loop had no error isolation. applyCorrection writes reserved_quantity as an absolute and is deliberately unguarded, so a row whose active holds sum past total_quantity — exactly the drift this job exists to find — makes the write violate chk_inventory_reserved_within_total and throw. Unhandled, that failed the whole job, and every BullMQ retry hit the same row first: nothing ordered after it was ever reconciled again.

Both are fixed. Each row now runs in its own try, matching the reservation sweeper, and the watermark is stamped outside it so a row that threw still advances — otherwise a poisoned row monopolises the front of the queue and reintroduces the same defect one row at a time.

9.2 A crashed import is recorded as failed, not left running

claim() flips the job row to processing before the import service runs, and everything before the write transaction — resolving the requester, reading the file, parsing, duplicate detection, product resolution — used to be unprotected. A throw there exited with no database write at all and the row stuck at processing.

That state could not be retried out of: the next attempt's claim() requires status = 'queued', finds processing, and returns false — and the processor returns rather than throwing, so BullMQ recorded a clean run and stopped. The job then sat at processing with no errors and no finished_at, indistinguishable from one still in flight. An upload removed between submit and pickup was enough.

run() now wraps the whole flow and records the failure before rethrowing, and the terminal status is forced to failed rather than derived from failedRows — on a crash no row was reached, so failedRows is 0, and deriving from it would have recorded a job that died reading its own file as completed.

  • Projection: via outbox after movements.
  • Both cron jobs enqueue directly (no DB write to be atomic with) — the documented exemption.
  • One worker per queue is the repo-wide rule — see BullMQ Worker Wiring.

10. Security and Authorization

  • Admin: JwtAuthGuard + RoleGuard; permissions Inventory_READ / Inventory_UPDATE; superadmin bypasses.
  • Import submit requires Inventory_UPDATE; export Inventory_READ; cancel Inventory_UPDATE.
  • Rate limits: ADMIN_READ 30/min, ADMIN_WRITE 10/min, ADMIN_BULK_WRITE 5/min, ADMIN_ASYNC_JOB_SUBMIT 10/hour.
  • InventoryWriteService is the only class permitted to UPDATE any column stock_status is generated from.
  • No guest surface exists; stock reaches customers through the product response only.

13. Error Handling

Error CodeHTTP StatusThrown ByConditionClient Action
CACHE_REVALIDATION_FAILEDNone (worker only, never returned to a client)InventoryStorefrontCacheProcessor.clearclearForWrite reported one or more Redis patterns it could not deleteNone. BullMQ retries; see 16.7
SYS_INTERNAL_ERROR500 if it ever surfacedInventoryLedgerService.markStorefrontStaleThe transaction-key SELECT returned no row (should not happen)Retry the request; report it

The clear never fails a request. It runs in a worker after commit, so a stock write that committed cannot 5xx because a cache did not clear.

14. Observability

All log lines come from the Logger of InventoryStorefrontCacheProcessor and carry txKey, which equals the outbox dedupe_key, so one grep follows a row, a job and a log line.

SignalLevelMeaning
[success] inventory_storefront_cache.clear jobId=... txKey=... cause=... waitedMs=... revalidation=...LOGA clear ran. The stamp was written, or its failure was warned about.
[skip] ... stamp=... createdAt=...DEBUGThe job was covered by an earlier clear.
[retry] ... attemptsMade=...WARNA clear failed and BullMQ will retry.
[failure] ... reason=final jobId=... txKey=... attemptsMade=... error=...ERRORThe job is finally failed (from job state). Staleness is now bounded by the 300 s TTL.
[failure] ... reason=job_unavailableERRORA failed event arrived with no job object.
[stalled] / [error] with queue=inventory_storefront_cacheERRORA stalled job, or a worker-level error.
[stamp] read failed, [stamp] write failed, [stamp] future-dated stamp ignoredWARNThe stamp was unavailable or unusable. The job clears anyway, so the effect is one extra clear.
Redis ERROR from RedisCacheServiceERRORExpected on the same path as a pattern failure.
... parked dead: ... from the outbox dispatcher, with job=inventory_storefront_cache.clearERRORThe relay failed on every attempt. That clear is lost (see 16.8).

There is no metric or scheduled dead-letter alert for this queue. A final failure is visible only as the ERROR line and the retained failed set.

16. Mandatory Backend Deep-Dive Pack

16.5 Business Logic and Invariant Catalog

InvariantEnforced ByWhy It ExistsFailure ErrorTests
A stock write that changes what the storefront shows records a stale row in the same transactionInventoryWriteService calls markStorefrontStaleThe clear cannot be forgotten or lost between commit and hookRollback discards the rowinventory-write.service.spec.ts, inventory-storefront-stale.int.spec.ts
One stale row per transactionOutbox unique key plus ON CONFLICT DO NOTHING, constant aggregateIdA bulk write must not enqueue N global wipesNoneinventory-storefront-stale.int.spec.ts
A reservation write emits only on a status-band crossing; finalize neverstockStatusTransitionedReserve and release on every checkout would wipe the cache constantlyNoneinventory-math.util.spec.ts, inventory-storefront-stale.int.spec.ts
The stamp is written only after a successful clearInventoryStorefrontCacheProcessor.clear step 6A failed clear must not make later jobs skipCACHE_REVALIDATION_FAILEDinventory-storefront-cache.processor.spec.ts
One worker, concurrency 1, on inventory_storefront_cacheINVENTORY_STOREFRONT_CACHE_WORKER_CONCURRENCY, queue-worker-uniqueness.spec.tsCoalescing assumes jobs run one at a timeNonequeue-worker-uniqueness.spec.ts
triggerForWrite stays fire-and-forgetRegression lock in cache-invalidation.service.spec.ts89 call sites in 45 production files rely on itNonecache-invalidation.service.spec.ts

16.6 Tradeoffs, Alternatives, and ADR Notes

DecisionContextChosen OptionAlternativesWhy ChosenTradeoffsRevisit Trigger
Where the stale event is recordedThe writer must emit without changing 13 writer and 10 ledger construction sitesA new method on the ledger, which already holds OutboxServiceOutboxService as a third writer constructor argument; an after-commit hook; reuse PROJECT_ACTIVITYSame-transaction durability with no constructor change. Drizzle has no commit hook, and PROJECT_ACTIVITY misses configuration changes and ties clears to MongoDB retriesOne extra SELECT and INSERT per emitting writeAn optional dedupeKey: SQL in the outbox would remove the SELECT
One row per transactionThe clear is a global wipeConstant aggregateId, transaction key as dedupe keyOne row per movement or per productCollapses imports and multi-line orders to one rowPayload describes only the first changePer-product cache keys
Dedicated queueAn inventory import backlog would delay clearsinventory_storefront_cache, concurrency 1A job on INVENTORYRemoves the inventory queue backlog from the lagOne more queue and env triple. The outbox FIFO still appliesOutbox priority for cache rows
CoalescingBursts of commits must not wipe the cache repeatedly2 s minimum interval with a trailing clear, stamp after successDebounce that drops the last change; clear every jobAt most 30 wipes per minute per worker, last change never droppedUp to 2 s added lagMeasured clear load
Failure surfaced to the handlertriggerForWrite swallows Redis failuresA separate clearForWrite that returns failed patternsA flag on triggerForWrite; change its contractNo change to the existing call sitesTwo similar methods to keep in stepA second queue handler needing it
Status-transition rule for reservationsCheckout reserve and release are the hottest writesEmit only on a band crossingEmit on every reservation writeKeeps clear requests lowExact reserved counts lag on the storefront until a crossingIf exact available counts must be live

16.7 Operational Runbook

OperationHow to InspectHealthy StateFailure SignalRecovery
Verify a clear after a stock writeFind the row: SELECT id, status FROM outbox_events WHERE job_name = 'inventory_storefront_cache.clear' ORDER BY id DESC LIMIT 5. Grep the API log for [success] inventory_storefront_cache.clear with that txKey. Check the keys: redis-cli --scan --pattern 'product:v2:*'Row dispatched, a [success] line, warmed keys goneRow stays pending or turns dead; no [success] lineSee the rows below
Outbox dispatchSame query. Run the API without API_RUNTIME_PROFILE=fastRows reach dispatched within one 5 s tick plus backlogRows stay pendingUnder API_RUNTIME_PROFILE=fast the scheduler never registers, so nothing dispatches. Restart without it. Otherwise raise OUTBOX_DISPATCH_BATCH_SIZE (max 500)
QueueBull Board, queue inventory_storefront_cacheJobs complete, failed set empty[retry] WARN lines, jobs in failedA Redis outage retries 5 times over about 15 s. After a final failure, delete the product:v2:* and catalog:search:* keys by hand or wait up to 300 s for the TTL
Dead outbox rowSELECT id, last_error FROM outbox_events WHERE status = 'dead' AND job_name = 'inventory_storefront_cache.clear'No rowsAny rowDead rows are never replayed automatically. Fix the cause (usually Redis or the queue), then clear the keys by hand. Staleness is bounded by 300 s

16.8 Backend Risk Register

RiskAreaImpactCurrent MitigationRemaining Gap
Clear lag after a cancel or inspection restockOutbox plus coalescingAbout 5 s stale stock, longer behind a large outbox backlogDedicated queue; configurable OUTBOX_DISPATCH_BATCH_SIZEThe outbox is one FIFO across all queues
Outbox row parked deadOutbox dispatcherThat clear is lost until the 300 s TTL. The dispatcher gives up after 3 attempts (the row's max_attempts default is 3; the global cap is 25)ERROR log with parked deadNo sweep or alert; no automatic replay
Final job failureinventory_storefront_cacheSame, bounded by 300 sERROR [failure] reason=final; failed set retained 48 hNo dead-letter alert
A reader caches stale data after the clearProduct readsA reader that read the database before commit can write the cache after the clearBounded by the 300 s TTLAccepted
Clock skew between dispatcher and workerCoalescingThe stamp is compared with job.timestamp; a skewed clock could skip or add a clear1000 ms skew allowance; a future-dated stamp is ignoredAssumes one clock for the dispatcher and the worker
No per-product cache keysCache designEvery clear wipes all product:v2:* and catalog:search:* keysCoalescing caps wipes at 30 per minute per workerPer-product keys

See Also