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
| Area | Files Inspected | Verified Details |
|---|---|---|
| Module wiring | inventory.module.ts, inventory-admin-aggregate.module.ts, inventory-import-export.module.ts, inventory-worker.module.ts, inventory-shared.module.ts | Composition, shared services |
| Controllers | admin/stock/*.controller.ts, admin/job/*.controller.ts | Route ownership, guards, permissions |
| Services | inventory-write.service.ts, inventory-reservation.service.ts, inventory-availability.service.ts, inventory-ledger.service.ts, inventory-projection.service.ts, inventory-job-lifecycle.service.ts | Guarded UPDATEs, lifecycle, projections |
| DTOs | dto/*.ts under each leaf | Validation |
| Schema | packages/db/src/schema/inventory/*.ts | Four tables, GENERATED columns, CHECKs |
| Jobs | packages/jobs/src/index.ts, workers/* | InventoryJob names, lease claim, scheduler |
| Cache | cache-invalidation.tags.ts, cache-invalidation.service.ts | inventory domain; triggerForWrite and clearForWrite |
| Storefront clear | inventory-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.ts | Per-transaction outbox row, dedicated queue, coalescing, retry options |
| Math | apps/api/src/utils/inventory/inventory-math.util.ts | Pure 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
INVENTORYqueue (one worker, five job names) and the maintenance scheduler. product.stock_statusas 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
productids, never the other way. - The outbox — generic infra; all enqueues go through it.
Source of Truth
| Concern | Source of Truth | Notes |
|---|---|---|
| Runtime state | PostgreSQL (inventory, inventory_reservation, inventory_movement, inventory_job) | |
| Availability | GENERATED columns — cannot be written | |
| Movement history | inventory_movement (same-tx) | Mongo is analytics only |
| Job state | inventory_job row + lease claim |
3. Module Composition
| Module | Type | Path | Controllers | Providers | Exports | Responsibility |
|---|---|---|---|---|---|---|
InventoryModule | Aggregate | inventory.module.ts | None | — | Leaves | Composes admin/worker/import-export |
InventoryAdminAggregateModule | Aggregate | admin/ | None | — | Leaves | Composes stock + job leaves |
InventoryStockAdminModule | Leaf | admin/stock/ | InventoryStockAdminController, InventoryStockAdminBulkController | Services | — | Stock surface |
InventoryJobAdminModule | Leaf | admin/job/ | InventoryJobAdminController | Service | — | Jobs surface |
InventoryImportExportModule | Leaf | import-export/ | None | Services | — | Import/export orchestration |
InventoryWorkerModule | Leaf | workers/ | None | Processor/handlers | — | Queue + scheduler |
InventorySharedModule | Leaf | shared/ | None | Write/Reservation/Ledger/Availability/Projection | Services | Shared 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 arithmeticKey files:
| File | Purpose | Key Exports | Notes |
|---|---|---|---|
shared/inventory-write.service.ts | The only writer of counter/config columns | InventoryWriteService | Guarded UPDATEs, variant_id ordering |
shared/inventory-variant-resolver.service.ts | The product → variant bridge | resolveStockVariant, 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.ts | Reservation lifecycle | InventoryReservationService | Global key, guarded transitions |
workers/inventory-queue.processor.ts | The one @Processor on INVENTORY | InventoryQueueProcessor | Routes via Record<InventoryJob, handler> |
import-export/inventory-job-lifecycle.service.ts | Job row transitions | claim, completeExport, failExport | Zero-row guard |
utils/inventory/inventory-math.util.ts | Pure stock arithmetic | deriveStockStatus, stockStatusTransitioned, canReserve, canDisableOversell | No NestJS imports |
shared/inventory-ledger.service.ts | Movement rows and the storefront-stale outbox row | InventoryLedgerService.record, markStorefrontStale | Constructor holds OutboxService only |
shared/inventory.constants.ts | Storefront clear constants | INVENTORY_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.ts | Coalesced storefront cache clear | InventoryStorefrontCacheProcessor | Calls 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.ts5.2 Tables
inventory
| Column | Type | Nullable | Default | Index/Constraint | Relation | Notes |
|---|---|---|---|---|---|---|
variant_id | integer | No | — | PK | product_variant.id | One 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_id | integer | No | — | FK, index, not unique | products.id | Denormalised 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_id | uuid | No | uuid7 | unique | — | The stock row's own identity, distinct from both ids above |
total_quantity | integer | No | 0 | CHECKs | — | Negative legal under allow_oversell (units owed) |
reserved_quantity | integer | No | 0 | CHECK >= 0 | — | |
available_quantity | integer | No | generated | — | — | GENERATED ALWAYS AS (total - reserved) — write attempt raises 428C9 |
stock_status | enum | No | generated | partial index WHERE stock_status = 'low_stock' | — | GENERATED CASE over counters |
track_inventory | boolean | No | true | — | — | Counters are authoritative unless turned off |
allow_oversell | boolean | No | false | — | — | |
low_stock_threshold | integer | No | 5 | CHECK >= 0 | — | Zero means "never warn" |
version | integer | No | 1 | CHECK >= 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
| Method | Called By | Reads | Writes | Side Effects | Errors |
|---|---|---|---|---|---|
createForProduct() | product create/import | — | inventory row (untracked) | — | — |
adjust() | admin adjust, import | row | counters + movement | projection (outbox), cache | INVENTORY_ADJUSTMENT_WOULD_GO_NEGATIVE, INVENTORY_INSUFFICIENT_STOCK |
updateConfiguration() | admin config | row + version | config fields (+ movement if counters change) | projection, cache | INVENTORY_VERSION_CONFLICT, INVENTORY_OVERSELL_DISABLE_BLOCKED |
bulkAdjust() | admin bulk | rows | counters + movements | projection, cache | per-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
| Method | Called By | Reads | Writes | Side Effects | Errors |
|---|---|---|---|---|---|
markStorefrontStale(executor, { productPublicId, cause, correlationId? }) | InventoryWriteService (adjustStock, applyReservationDelta, updateConfiguration, applyCorrection) | pg_current_xact_id() and now() of the caller's transaction | One outbox_events row (INSERT ... ON CONFLICT DO NOTHING) | The dispatcher relays the row to the inventory_storefront_cache queue after commit | SYS_INTERNAL_ERROR if the key query returns no row (should not happen) |
How it works (inventory-ledger.service.ts:173-207):
- 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. OutboxService.enqueuewrites the row withaggregateType: "inventory", the constantaggregateId"storefront",eventType: "inventory.storefront_stale",jobName: InventoryStorefrontCacheJob.CLEAR, and the transaction key asdedupeKey.- 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 oneSELECTand oneINSERTper row but leaves one row. - 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.
| Method | Called By | Reads | Writes | Side Effects | Errors |
|---|---|---|---|---|---|
clear(job) | process | Redis stamp inventory:storefront:cleared_from | The 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 event | await job.isFailed() | None | ERROR log on final failure, WARN on retry | None |
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.
- 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.
- Covered: skip. If
stamp - 1000 ms > T, a clear began after this job existed, so the job returns (DEBUG[skip]). - 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. - Clear. Capture
start = Date.now(), then callclearForWrite({ domain: "inventory", entityId: productPublicId, reason: "inventory_<cause>" }). - Fail loudly. If
redisPatternsFailedis not empty, throw witherrorCode: CACHE_REVALIDATION_FAILED. The stamp is not written, so BullMQ's retry and every later job still clear. - Stamp after success. Write
startto the stamp key withCACHE_TTL.VOLATILE(30 s). A failed write is a WARN, not a throw: a missing stamp only causes one extra clear. - 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) | |
|---|---|---|
| Source | cache-invalidation.service.ts:111 | cache-invalidation.service.ts:125 |
| Returns | Promise<void> | Promise<CacheWriteClearOutcome> |
| Redis pattern failure | Logged, swallowed | Returned in redisPatternsFailed |
| Unexpected throw | Swallowed by revalidateWriteHook | Propagates to the caller |
| Next.js revalidation failure | Maintenance-queue retry | Same retry, reported as revalidationRetryQueued |
| Use from | Request 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.
| Step | Code Path | Behavior | Failure Case |
|---|---|---|---|
| 1 | InventoryWriteService (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. |
| 2 | InventoryLedgerService.markStorefrontStale | One outbox row per transaction. | Outbox insert error aborts the caller's transaction. |
| 3 | Outbox dispatcher | Relays the row to the dedicated queue after commit. | A relay failure retries; after 3 attempts the row is dead (see 16.8). |
| 4 | InventoryStorefrontCacheProcessor.clear | Coalesces, then calls clearForWrite. | A Redis pattern failure throws, and BullMQ retries. |
| 5 | BullMQ options | 5 attempts, exponential backoff from 1000 ms. | Final failure stays in the failed set with an ERROR log. |
Which writes emit.
| Writer method | Emits when | cause |
|---|---|---|
adjustStock | Always, after a successful guarded UPDATE | adjustment |
applyCorrection | Only when a movement row was recorded (not on the zero-delta early return) | correction |
updateConfiguration | Always on success, including a body that carries only version | configuration |
applyReservationDelta (reserve, release, expire, finalize) | Only if stockStatusTransitioned(row, delta) is true | the 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_stocktoin_stock) emits nothing. - Finalize never emits. It moves total and reserved together, so
availableis 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.
createForVariantdoes 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
availableis 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):
| Component | Bound |
|---|---|
| Wait for the next outbox tick | up to 5 s (OUTBOX_DISPATCH_INTERVAL_MS) |
| Outbox backlog ahead of the row | 100 rows per 5 s pass by default (OUTBOX_DISPATCH_BATCH_SIZE, configurable up to 500) |
| Coalescing wait | up to 2 s |
| Clear duration | the 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 Pattern | Builder | Value | TTL | Invalidation | Caller |
|---|---|---|---|---|---|
product:v2:* (product cards, variant availability) | the products module | cached product reads carrying stock | existing (CACHE_TTL.STANDARD, 300 s) | inventory domain clear | InventoryStorefrontCacheProcessor through clearForWrite; the request-path triggers in 7.3 through triggerForWrite |
catalog:search:* | the catalog module | search results carrying stock status | existing | same | same |
inventory:storefront:cleared_from | CacheKeyUtil.build(INVENTORY_CACHE_PREFIX, [["storefront","cleared_from"]]) | epoch ms: start time of the last successful clear | CACHE_TTL.VOLATILE (30 s) | Overwritten after each successful clear | InventoryStorefrontCacheProcessor |
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
inventorygroup are refreshed the same way. - The wipe is global. Cache keys are not per product, so
entityIdis 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
| Queue | Dispatcher | Job names |
|---|---|---|
INVENTORY | inventory-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.
| Option | Default | Env key |
|---|---|---|
| attempts | 5 | BULL_QUEUE_INVENTORY_STOREFRONT_CACHE_ATTEMPTS |
| backoff | exponential, 1000 ms (about 15 s of retries) | BULL_QUEUE_INVENTORY_STOREFRONT_CACHE_BACKOFF_DELAY_MS |
| removeOnComplete count | 1000 | BULL_QUEUE_INVENTORY_STOREFRONT_CACHE_REMOVE_ON_COMPLETE_COUNT |
| removeOnComplete age | inherited, 7200 s | BULL_DEFAULT_REMOVE_ON_COMPLETE_AGE_SEC |
| removeOnFail age and count | inherited, 172800 s and 5000 | BULL_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 carriestotal_rows+result_file_urltogether;failExportnever 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_aftermatches counters; repairs withcorrectionmovements, 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; permissionsInventory_READ/Inventory_UPDATE;superadminbypasses. - Import submit requires
Inventory_UPDATE; exportInventory_READ; cancelInventory_UPDATE. - Rate limits:
ADMIN_READ30/min,ADMIN_WRITE10/min,ADMIN_BULK_WRITE5/min,ADMIN_ASYNC_JOB_SUBMIT10/hour. InventoryWriteServiceis the only class permitted to UPDATE any columnstock_statusis generated from.- No guest surface exists; stock reaches customers through the product response only.
13. Error Handling
| Error Code | HTTP Status | Thrown By | Condition | Client Action |
|---|---|---|---|---|
CACHE_REVALIDATION_FAILED | None (worker only, never returned to a client) | InventoryStorefrontCacheProcessor.clear | clearForWrite reported one or more Redis patterns it could not delete | None. BullMQ retries; see 16.7 |
SYS_INTERNAL_ERROR | 500 if it ever surfaced | InventoryLedgerService.markStorefrontStale | The 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.
| Signal | Level | Meaning |
|---|---|---|
[success] inventory_storefront_cache.clear jobId=... txKey=... cause=... waitedMs=... revalidation=... | LOG | A clear ran. The stamp was written, or its failure was warned about. |
[skip] ... stamp=... createdAt=... | DEBUG | The job was covered by an earlier clear. |
[retry] ... attemptsMade=... | WARN | A clear failed and BullMQ will retry. |
[failure] ... reason=final jobId=... txKey=... attemptsMade=... error=... | ERROR | The job is finally failed (from job state). Staleness is now bounded by the 300 s TTL. |
[failure] ... reason=job_unavailable | ERROR | A failed event arrived with no job object. |
[stalled] / [error] with queue=inventory_storefront_cache | ERROR | A stalled job, or a worker-level error. |
[stamp] read failed, [stamp] write failed, [stamp] future-dated stamp ignored | WARN | The stamp was unavailable or unusable. The job clears anyway, so the effect is one extra clear. |
Redis ERROR from RedisCacheService | ERROR | Expected on the same path as a pattern failure. |
... parked dead: ... from the outbox dispatcher, with job=inventory_storefront_cache.clear | ERROR | The 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
| Invariant | Enforced By | Why It Exists | Failure Error | Tests |
|---|---|---|---|---|
| A stock write that changes what the storefront shows records a stale row in the same transaction | InventoryWriteService calls markStorefrontStale | The clear cannot be forgotten or lost between commit and hook | Rollback discards the row | inventory-write.service.spec.ts, inventory-storefront-stale.int.spec.ts |
| One stale row per transaction | Outbox unique key plus ON CONFLICT DO NOTHING, constant aggregateId | A bulk write must not enqueue N global wipes | None | inventory-storefront-stale.int.spec.ts |
| A reservation write emits only on a status-band crossing; finalize never | stockStatusTransitioned | Reserve and release on every checkout would wipe the cache constantly | None | inventory-math.util.spec.ts, inventory-storefront-stale.int.spec.ts |
| The stamp is written only after a successful clear | InventoryStorefrontCacheProcessor.clear step 6 | A failed clear must not make later jobs skip | CACHE_REVALIDATION_FAILED | inventory-storefront-cache.processor.spec.ts |
One worker, concurrency 1, on inventory_storefront_cache | INVENTORY_STOREFRONT_CACHE_WORKER_CONCURRENCY, queue-worker-uniqueness.spec.ts | Coalescing assumes jobs run one at a time | None | queue-worker-uniqueness.spec.ts |
triggerForWrite stays fire-and-forget | Regression lock in cache-invalidation.service.spec.ts | 89 call sites in 45 production files rely on it | None | cache-invalidation.service.spec.ts |
16.6 Tradeoffs, Alternatives, and ADR Notes
| Decision | Context | Chosen Option | Alternatives | Why Chosen | Tradeoffs | Revisit Trigger |
|---|---|---|---|---|---|---|
| Where the stale event is recorded | The writer must emit without changing 13 writer and 10 ledger construction sites | A new method on the ledger, which already holds OutboxService | OutboxService as a third writer constructor argument; an after-commit hook; reuse PROJECT_ACTIVITY | Same-transaction durability with no constructor change. Drizzle has no commit hook, and PROJECT_ACTIVITY misses configuration changes and ties clears to MongoDB retries | One extra SELECT and INSERT per emitting write | An optional dedupeKey: SQL in the outbox would remove the SELECT |
| One row per transaction | The clear is a global wipe | Constant aggregateId, transaction key as dedupe key | One row per movement or per product | Collapses imports and multi-line orders to one row | Payload describes only the first change | Per-product cache keys |
| Dedicated queue | An inventory import backlog would delay clears | inventory_storefront_cache, concurrency 1 | A job on INVENTORY | Removes the inventory queue backlog from the lag | One more queue and env triple. The outbox FIFO still applies | Outbox priority for cache rows |
| Coalescing | Bursts of commits must not wipe the cache repeatedly | 2 s minimum interval with a trailing clear, stamp after success | Debounce that drops the last change; clear every job | At most 30 wipes per minute per worker, last change never dropped | Up to 2 s added lag | Measured clear load |
| Failure surfaced to the handler | triggerForWrite swallows Redis failures | A separate clearForWrite that returns failed patterns | A flag on triggerForWrite; change its contract | No change to the existing call sites | Two similar methods to keep in step | A second queue handler needing it |
| Status-transition rule for reservations | Checkout reserve and release are the hottest writes | Emit only on a band crossing | Emit on every reservation write | Keeps clear requests low | Exact reserved counts lag on the storefront until a crossing | If exact available counts must be live |
16.7 Operational Runbook
| Operation | How to Inspect | Healthy State | Failure Signal | Recovery |
|---|---|---|---|---|
| Verify a clear after a stock write | Find 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 gone | Row stays pending or turns dead; no [success] line | See the rows below |
| Outbox dispatch | Same query. Run the API without API_RUNTIME_PROFILE=fast | Rows reach dispatched within one 5 s tick plus backlog | Rows stay pending | Under API_RUNTIME_PROFILE=fast the scheduler never registers, so nothing dispatches. Restart without it. Otherwise raise OUTBOX_DISPATCH_BATCH_SIZE (max 500) |
| Queue | Bull Board, queue inventory_storefront_cache | Jobs complete, failed set empty | [retry] WARN lines, jobs in failed | A 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 row | SELECT id, last_error FROM outbox_events WHERE status = 'dead' AND job_name = 'inventory_storefront_cache.clear' | No rows | Any row | Dead 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
| Risk | Area | Impact | Current Mitigation | Remaining Gap |
|---|---|---|---|---|
| Clear lag after a cancel or inspection restock | Outbox plus coalescing | About 5 s stale stock, longer behind a large outbox backlog | Dedicated queue; configurable OUTBOX_DISPATCH_BATCH_SIZE | The outbox is one FIFO across all queues |
Outbox row parked dead | Outbox dispatcher | That 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 dead | No sweep or alert; no automatic replay |
| Final job failure | inventory_storefront_cache | Same, bounded by 300 s | ERROR [failure] reason=final; failed set retained 48 h | No dead-letter alert |
| A reader caches stale data after the clear | Product reads | A reader that read the database before commit can write the cache after the clear | Bounded by the 300 s TTL | Accepted |
| Clock skew between dispatcher and worker | Coalescing | The stamp is compared with job.timestamp; a skewed clock could skip or add a clear | 1000 ms skew allowance; a future-dated stamp is ignored | Assumes one clock for the dispatcher and the worker |
| No per-product cache keys | Cache design | Every clear wipes all product:v2:* and catalog:search:* keys | Coalescing caps wipes at 30 per minute per worker | Per-product keys |
See Also
- Worker wiring: BullMQ Worker Wiring
- Order cancellation and return inspection: Order Backend
- POS triggers: POS Backend
- API doc:
/docs/developer/inventory/api - Features and flows doc:
/docs/developer/inventory/feature