Payments and Dispatch: Two Workflows That Have to Agree

A service order connecting a technician dispatch map to timed marketplace payment transfers.
Concept illustration: dispatch and payment workflows meet at the same service order.

A service marketplace has two promises to keep: the right technician should receive the job, and the right account should receive the money. Those promises look separate in a feature list. In the backend, they meet at the same order record.

While building consumer and technician apps, I worked with Node.js, Firebase, Stripe Connect, and location-based dispatch. These integrations brought concurrency and recovery into the same workflow: two functions can run together, an event can arrive twice, or a process can stop halfway through. Here is how I would extend the design to handle those cases.


Model the money precisely

A customer payment, a transfer to a connected Stripe account, and a payout to a bank account are different operations. A successful payment does not prove that either later step has completed. Stripe’s manual payout documentation distinguishes these operations and explicitly states that Stripe does not provide escrow services.

For a workflow that schedules technician earnings after service completion, the application needs its own durable transfer record. That record should reference the order, payment, destination account, amount, currency, eligibility time, and processing status. Payment metadata helps connect systems; it should not replace the application’s transaction history.

The scheduler needs to do more than query pending records and call an API. Two workers may find the same record. A worker may create the transfer successfully and crash before saving the result. I would claim work atomically and assign one persisted operation ID to each intended transfer. Every retry of that transfer must keep the same ID and parameters.

Stripe’s idempotency documentation explains that keys can be pruned after at least 24 hours. The application therefore needs both retry protection and a permanent transfer record. An old or ambiguous attempt needs reconciliation before another transfer is created.

Here is an illustrative API call, assuming the server has already validated the order and claimed the transfer job:

const transfer = await stripe.transfers.create(
  {
    amount: job.amountMinorUnits,
    currency: job.currency,
    destination: job.connectedAccountId,
    metadata: { orderId: job.orderId },
  },
  { idempotencyKey: `transfer:${job.transferOperationId}` }
);
// Persist transfer.id before marking this job complete.

The amount comes from trusted server data. A client should not decide what another account receives. The server must also account for funds availability and transfer failures. For separate charges and transfers, refunding a charge does not reverse its associated transfers. Reconciliation and transfer reversals need their own policy.


Use distance as a filter, not a travel estimate

The dispatch logic used latitude and longitude to identify nearby opportunities. Haversine distance is useful here because it estimates great-circle distance on a sphere. Google Maps’ spherical geometry guide describes the same kind of geographic distance measurement. It does not account for roads, traffic, bridges, or a technician’s actual route.

A small illustrative helper makes the unit visible:

function distanceMiles(a, b) {
  const rad = degrees => degrees * Math.PI / 180;
  const dLat = rad(b.latitude - a.latitude);
  const dLon = rad(b.longitude - a.longitude);
  const h = Math.sin(dLat / 2) ** 2
    + Math.cos(rad(a.latitude)) * Math.cos(rad(b.latitude))
    * Math.sin(dLon / 2) ** 2;
  const bounded = Math.min(1, Math.max(0, h));
  return 3958.8 * 2 * Math.atan2(Math.sqrt(bounded), Math.sqrt(1 - bounded));
}

Location freshness matters as much as the formula. A coordinate should carry a timestamp and accuracy information. An old location is weak evidence of current availability.


Keep eligibility separate from ownership

The Firebase approach maintained nearby-order views as orders and technician locations changed. That makes the mobile feed responsive, but it introduces duplicated data and fan-out work. A materialized feed can briefly be stale, and scanning every technician or active order becomes increasingly expensive as those collections grow.

The acceptance endpoint must therefore recheck eligibility and current order state. Two technicians can see the same opportunity; only one should acquire it. A conditional update or transaction should determine the winner. The transaction prevents double assignment; removing the order from everyone else’s feed keeps the visible data consistent afterward.

Firestore transaction callbacks can run again when a concurrent update changes a document they read. I would keep Stripe calls and push notifications outside that callback, after the database decision has committed, rather than accidentally repeating an external operation during a retry.


Debug the whole order

I find an order ID more useful than disconnected success logs. It should connect dispatch decisions, payment references, status changes, transfer attempts, and errors without exposing private message content or financial credentials.

These flows changed what I look for in a backend review. I want to know which record decides ownership, how an uncertain payment attempt is recovered, and what evidence connects the result back to the order. A successful demo is useful; an interrupted request is often the more revealing test.