DEV Community

Prism Thread Journal
Prism Thread Journal

Posted on

Webhook Idempotency for China 3PL Order Intake

A storefront retries a webhook when the response is lost. The warehouse receives the retry, creates another fulfillment, reserves the stock again, and prints a second label. The original order may look successful while the physical operation has silently doubled.

Idempotency prevents that outcome by making the business action depend on a durable identity rather than on how many times a request arrives. For a China 3PL integration, the identity must cover the sales channel and external order, while the processing record must distinguish a harmless retry from a conflicting update.

YX Fulfillment supports order intake through project-specific files, APIs, built-in connections, or manual entry. Its integration and account support service includes mapping, duplicate handling, rejected orders, and trial verification. The implementation below is a synthetic engineering pattern for a team designing its own middleware. It is not a published YX Fulfillment API specification.

Choose the Idempotency Scope Before Writing Code

An idempotency key should identify one intended fulfillment action. For a simple order, the channel plus external order ID is often the right business scope. A global key based only on the request payload is unsafe because two legitimate orders can contain identical items and addresses.

Keep the transport event ID as a separate field when the channel provides one. Event IDs help trace deliveries, but they do not always replace the order-level identity. One order can generate several events for edits, risk release, or cancellation.

Use a request hash to detect conflicting reuse. If the same idempotency identity arrives with a different SKU, quantity, or address, return a conflict for review instead of treating it as a routine retry. Legitimate order edits need their own versioned action or an explicit update workflow.

Persist the Identity With the Fulfillment Record

An in-memory cache is not enough. The process can restart between receiving a request and writing the fulfillment. The uniqueness rule therefore belongs in the database that owns the fulfillment action.

The following PostgreSQL DDL is a synthetic starting point. Adapt names and constraints to the actual service.

CREATE TABLE fulfillment_receipt (
    order_identity TEXT PRIMARY KEY,
    source_channel TEXT NOT NULL,
    external_order_id TEXT NOT NULL,
    idempotency_key TEXT NOT NULL UNIQUE,
    request_hash TEXT NOT NULL,
    fulfillment_id TEXT NOT NULL,
    order_version INTEGER NOT NULL,
    received_at TIMESTAMPTZ NOT NULL
)
Enter fullscreen mode Exit fullscreen mode

The application builds order_identity from the normalized source channel and external order ID. Its primary key blocks two active fulfillment records for the same channel order. The unique idempotency key catches accidental identity reuse across another order. In a production design, the fulfillment ID should reference the operational order table through the appropriate relational constraint.

Do not mark the request complete before its operational writes are durable. Insert the receipt, create or retrieve the fulfillment, allocate inventory, and enqueue warehouse work within a transaction where the data model permits it. If any required step fails, roll back the unit of work so a retry can start cleanly.

Handle Concurrent Retries as a Database Outcome

Two workers can receive the same request at the same time. Checking for an existing row and then inserting it leaves a race unless the database enforces uniqueness.

A safe processing sequence is:

  1. Validate the payload and normalize the business identity.
  2. Attempt to insert the fulfillment receipt with its unique constraints.
  3. If the insert succeeds, create the operational fulfillment and continue.
  4. If a uniqueness conflict occurs, read the existing receipt.
  5. Compare the request hash and order version.
  6. Return the existing fulfillment for an exact retry or raise a conflict for a different action.

The exact SQL and transaction boundary depend on the database. The important behavior is that the database, not a timing assumption, decides which request created the action. Lock the existing fulfillment while applying any later authorized update so a retry cannot race with a cancellation.

Separate Acceptance, Allocation, and Carrier Handover

An accepted webhook does not mean inventory has been allocated. An allocated order does not mean it has been packed. A generated label does not prove carrier handover. Persist these as different events with different timestamps.

Event Durable evidence Safe retry behavior
Request accepted Receipt row with request hash Return the same receipt
Fulfillment created Operational order reference Retrieve rather than recreate
Stock reserved Allocation record tied to the fulfillment Reconcile quantity without a second deduction
Parcel packed Package and label records Reuse the existing package identity
Carrier accepted Handover scan or manifest evidence Update tracking without creating another parcel

This separation matters when a warehouse response is delayed. The middleware should not infer carrier possession from a label response. It should store the status supplied by the responsible system and keep an audit trail of transitions.

Use an Outbox for Warehouse and Channel Write-Back

After committing the order, publish work through a transactional outbox or an equivalent durable queue pattern. Write the outbox record in the same transaction as the fulfillment. A background worker can then deliver it and retry without losing the connection between database commit and message publication.

Consumers also need idempotency. A warehouse worker may receive the same job twice, and a storefront may receive the same tracking callback twice. Use the fulfillment and package identities to make both consumers safe. A tracking callback should update the matching package rather than create a new shipment.

Set retry limits and a visible dead-letter path. Repeated failures need an operator alert and a preserved payload. Silent retries can leave an order accepted by the storefront but absent from the warehouse queue.

Test the Failure Windows, Not Only the Happy Path

Use synthetic orders and controlled failures to exercise the risky intervals.

Test Injected condition Required result
Response lost Commit succeeds but the client receives a timeout Retry returns the original fulfillment
Concurrent delivery Two workers submit the same identity together One fulfillment and one allocation exist
Payload conflict Same identity arrives with a changed quantity Conflict is recorded and no silent update occurs
Worker restart Process stops after commit but before queue publication Outbox delivers the pending job
Callback replay Storefront acknowledgment is lost Tracking converges without another parcel
Late cancellation Cancellation arrives after allocation Approved intercept rule determines the final state

Assert database rows, inventory movement, package count, and callback values. A successful HTTP status alone is not an adequate test result.

Before launch, replay the suite against the actual account permissions, channel mappings, warehouse node, and carrier service. Review YX Fulfillment's operating process alongside the integration contract so order release, warehouse cutoff, and carrier handover remain separate operational events.

Top comments (0)