KeldroveOpen dashboard
Keldrove / Merchant guides

Design a Node.js worker for invoice updates

A crypto checkout written in Node.js must keep its payment decisions when a process restarts or events arrive twice. Keldrove proposes signed invoice notifications for assets including Monero. This guide uses a local reducer to model the store’s decisions, then explains which guarantees need a database when a real merchant integration becomes available.

By the Published · Updated

Put the durable boundary before the queue worker

A small shop sells downloadable map packs. Its Express or other HTTP application creates an order, its worker contacts a gateway and its fulfillment service creates the download entitlement. If all pending invoices exist only in a JavaScript Map, a deployment can erase the relationship between a real payment and its customer.

Start with an orders table, an invoice-attempt record and a persistent job queue or an outbox table.

The order owns the agreed price and customer entitlement. The attempt owns the body and idempotency key used to create an invoice. The inbox records verified provider events. The fulfillment record says which order has actually received its download. A process can restart between any two of these actions. Give each a stable reference and define what a new worker should find when it picks up unfinished work.

Try state transitions without a remote service

The following pure function works on illustrative objects. Run a fixture with revision three detected, then revision four confirmed, then a replay of revision three. The first case moves the tracked revision forward and the second records eligibility for a release. The older event leaves the state alone.

A review arriving at revision five should remain visible after an entitlement is granted.

function applyInvoice(current, invoice) {
  if (invoice.id !== current.invoiceId ||
      invoice.store_id !== current.storeId ||
      invoice.order_ref !== current.orderRef ||
      invoice.price.currency !== "USD" ||
      invoice.price.amount !== current.expectedUsd) {
    throw new Error("Invoice does not match the saved order");
  }
  if (invoice.revision <= current.revision) return current;

  return {
    ...current,
    revision: invoice.revision,
    paymentState: invoice.status,
    needsRelease: invoice.status === "confirmed" && !current.fulfilled
  };
}

The input is a normalized, authenticated invoice read, with validated field types and a supported state. The fixture prices use canonical decimal strings in the proposed API format. The reducer compares a saved order and invoice and calculates an action. A real worker still needs a unique fulfillment key, an atomic update and a separate record of actual delivery. Writing a Boolean into a JavaScript object cannot ensure that two independent processes will issue only one download.

Plan for cancellation and uncertain timeouts

Node’s global fetch supports a cancellation signal. A deadline can free the merchant process when an external request stalls. A timeout says the caller stopped waiting. It does not establish whether the receiver processed the request. Save the attempt before sending and retry the same request under the same key.

A new key after a timeout can create two active invoices for the same order. Node.js globals and fetch.

Decide how jobs are leased. A worker can disappear after creating a remote invoice but before saving the response. Another worker must be able to claim the expired job and recover the original invoice. Use a bounded deadline and retry policy per attempt. Expose a support intervention after repeated failures instead of telling a customer their purchase is definitely unpaid when the server has an uncertain result.

Validate the callback before parsing business fields

Read the unchanged request body before processing invoice fields. The proposed signature covers the timestamp and those exact bytes. After the signature check, store the event ID and the invoice revision together so that repeated notifications cannot unlock the same order twice.

The incoming HTTP request needs its original body bytes for the proposed HMAC signature. Configure the callback route so the framework preserves those bytes before conventional JSON parsing. Keep signer verification separate from event storage and business decisions. A failure should record a diagnostic reason such as stale delivery or bad signature, without leaking the endpoint secret or the whole checkout link.

After verification, insert the provider’s event ID and its queued work in a durable operation. If a duplicate violates the event uniqueness constraint, acknowledge a previously committed event. The worker should fetch the current invoice and call the same order validation used by periodic reconciliation. Node’s crypto library provides HMAC and constant-time comparison primitives, but correct byte handling and per-store key selection still belong to your application. Node.js cryptographic primitives.

Recover fulfillment after a restart

A restarted worker should recover the order from durable records. The last callback a process remembers cannot tell a replacement process whether stock was already released. Rebuild the decision from the stored event, the latest invoice revision and the store’s own fulfillment record.

What a fresh Node.js worker should recover after each interruption
Process stopped afterDurable evidenceRecovery
Saving the checkout attemptOrder, request body and idempotency keyResume the same creation job.
Receiving an eventVerified inbox entry and a pending work itemRead the current invoice.
Recording confirmationSaved revision plus an entitlement jobIssue the download using the order’s unique release key.
Sending the entitlementIdempotent delivery referenceReconcile the existing delivery before sending again.

Some external systems cannot guarantee exactly-once delivery of an email or a webhook. Make the valuable action itself idempotent. For example, let repeated notifications give access to the same already-issued map entitlement. Do not issue a new paid license on each transport attempt. Keep a visible record when an outside system acknowledged a request but delivery to a person remains uncertain.

Test concurrency with two real worker instances

A unit test of the reducer will show what should happen when revisions arrive in reverse order. A concurrency test with two workers should show that only one release row can commit for the order. Add a fixture where a new review revision arrives while an earlier release is already recorded.

A finance queue should see the review without deleting the customer’s earlier delivery record.

Measure time spent waiting on external invoice reads separately from queue wait and entitlement processing. A customer-facing status can say that an order is awaiting network confirmation or that a confirmed payment is awaiting delivery. Those are different operational problems with different owners. The proposed Keldrove API belongs to Pro and Business. The public site supplies design examples while credentials, access, callback delivery and production performance are pending implementation.

Questions merchants ask

Is the reducer a complete gateway integration?

It is a local example of order and revision checks. Authentication, schema validation, durable transactions, queue recovery and the provider’s actual service would still be required.

Can I store open invoices in memory?

An in-memory cache can accelerate reads. Store the order, invoice attempt, idempotency key and fulfillment history durably so that deployments and worker restarts remain recoverable.

Why keep a review after a successful delivery?

A later chain event or discrepancy can change the payment evidence. Keep that case available to operations while preserving the record of the entitlement already granted.

Merchant terms at a glance
Subscription currencies
BTC, LTC, ETH, SOL, USDC on Ethereum, USDT on Ethereum or Tron, and Monero (XMR).
Account
Register with an email and password or a private account code. No identity document is requested.
Price on 2026-11-27
$25 for Starter per 30 days. Keldrove charges only the subscription, with 0% transaction fees on every plan. The subscription funding minimum is $25. Customer invoices have separate network limits.
Activation
Create an order at checkout. Activation follows payment verification.
Compare three published gateway fee models
Provider pricing checked November 27, 2026, excluding network costs
ProviderService fee basis
CryptAPI1% in the entry volume band.
BitPay2% plus 25¢ per transaction under $500,000 monthly volume. Higher-risk industries may pay more.
BTCPay Server0% software processing fee. Operating or renting a server carries separate costs.