whereparcel

Stuck on integration? Have a question? The developer is standing by.

Tutorial 7 min read

How to Build Real-Time Delivery Estimates with Tracking Data

Learn how to use package tracking events to calculate and display accurate estimated delivery dates in your application, improving customer satisfaction.

WhereParcel Team

One of the most common questions customers ask is “When will my package arrive?” While carriers provide estimated delivery dates, they’re often vague or inaccurate. By analyzing real-time tracking events, you can build smarter, more accurate delivery estimates that keep customers informed and reduce support inquiries.

Why Standard ETAs Fall Short

Most carrier-provided ETAs are set at the time of shipment and rarely update. They don’t account for:

  • Customs delays for international shipments
  • Weather-related disruptions
  • Carrier sorting facility backlogs
  • Last-mile delivery challenges

By processing real-time tracking events, you can dynamically adjust estimates as packages move through the delivery network.

Setting Up Tracking Event Collection

First, subscribe to tracking updates using WhereParcel webhooks. Subscribed parcels are re-checked on every polling cycle, every several hours; when a customer opens the tracking page, a POST /v2/track call gives you the freshest data:

const headers = {
  'Authorization': 'Bearer YOUR_API_KEY:YOUR_SECRET_KEY',
  'Content-Type': 'application/json',
};

// 1. Create a webhook endpoint once (free). Keep endpointId, and store the
//    returned secret to verify X-WhereParcel-Signature on incoming webhooks.
const endpoint = await fetch('https://api.whereparcel.com/v2/webhook-endpoints', {
  method: 'POST',
  headers,
  body: JSON.stringify({
    name: 'Delivery estimates',
    url: 'https://your-app.com/webhooks/tracking',
    description: 'Tracking status updates',
  }),
}).then((r) => r.json());

// 2. Subscribe each shipment (billed once per parcel, up to 100 per call).
//    recurring: true keeps re-checking it until it is delivered.
await fetch('https://api.whereparcel.com/v2/webhooks/register', {
  method: 'POST',
  headers,
  body: JSON.stringify({
    webhookEndpointId: endpoint.data.endpointId,
    recurring: true,
    trackingItems: [{ carrier: 'us.usps', trackingNumber: '9400111899562537866361' }],
  }),
});

Processing Events for ETA Calculation

Each tracking event contains status information and timestamps that you can use to build estimates. When the carrier publishes its own delivery date, WhereParcel passes it through as estimatedDelivery; not every carrier does, so treat it as one input rather than the answer:

// trackingData = item.trackingData from a webhook, or data[0].data from POST /v2/track
function calculateEstimatedDelivery(trackingData, carrier, destination) {
  const { events, estimatedDelivery } = trackingData;
  const latestEvent = events[events.length - 1];   // events are oldest first

  // Base estimates by standardized status
  // (there is no picked_up or customs status: the first scan after
  //  the label is created already reports in_transit)
  const estimateMap = {
    'pending': { minDays: 2, maxDays: 6 },          // label created, not scanned yet
    'in_transit': { minDays: 1, maxDays: 3 },
    'out_for_delivery': { minDays: 0, maxDays: 0 },
  };

  const estimate = estimateMap[latestEvent.status] || { minDays: 2, maxDays: 7 };

  const now = new Date();
  return {
    earliest: addBusinessDays(now, estimate.minDays),
    latest: addBusinessDays(now, estimate.maxDays),
    confidence: calculateConfidence(events),
    // The carrier's own date, when it publishes one (optional field)
    carrierDate: estimatedDelivery ? new Date(estimatedDelivery) : null,
  };
}

Building an Adaptive Estimation Model

For more accurate estimates, track historical delivery times by carrier and route:

// Store delivery times for completed shipments
async function recordDeliveryTime(shipment) {
  // First scan after the label was created (there is no picked_up status)
  const pickupDate = shipment.events.find(e => e.status !== 'pending')?.timestamp;
  const deliveryDate = shipment.events.find(e => e.status === 'delivered')?.timestamp;

  if (pickupDate && deliveryDate) {
    await db.deliveryTimes.insert({
      carrier: shipment.carrier,
      originCountry: shipment.origin.country,
      destinationCountry: shipment.destination.country,
      transitDays: daysBetween(pickupDate, deliveryDate),
      recordedAt: new Date(),
    });
  }
}

// Calculate average delivery time for a route
async function getHistoricalAverage(carrier, origin, destination) {
  const records = await db.deliveryTimes
    .find({ carrier, originCountry: origin, destinationCountry: destination })
    .sort({ recordedAt: -1 })
    .limit(100);

  if (records.length < 10) return null; // Not enough data

  const times = records.map(r => r.transitDays);
  return {
    average: Math.round(times.reduce((a, b) => a + b) / times.length),
    p90: percentile(times, 90),
    sampleSize: records.length,
  };
}

Displaying Estimates in Your UI

Present delivery estimates clearly with appropriate confidence levels:

function DeliveryEstimate({ estimate }) {
  const { earliest, latest, confidence } = estimate;

  if (confidence === 'high') {
    return (
      <div className="estimate high-confidence">
        <span>Expected delivery: {formatDate(earliest)}</span>
      </div>
    );
  }

  return (
    <div className="estimate">
      <span>
        Estimated delivery: {formatDate(earliest)} – {formatDate(latest)}
      </span>
      {confidence === 'low' && (
        <small>Estimate may change based on customs processing</small>
      )}
    </div>
  );
}

Handling Edge Cases

International Shipments with Customs

Customs processing is the biggest variable in delivery estimates. When a package enters customs, widen your estimate range:

// No customs status exists: customs scans arrive as in_transit
// with the carrier's wording in description
if (latestEvent.status === 'in_transit' && /customs|clearance/i.test(latestEvent.description)) {
  // Customs can take 1-14 days depending on country
  estimate.latest = addBusinessDays(now, getCustomsEstimate(destination.country));
  estimate.confidence = 'low';
}

Delivery Exceptions

When tracking shows a failed delivery attempt or exception, update the estimate accordingly:

// A missed attempt the carrier will retry usually stays in_transit (USPS: "Notice Left")
if (/notice left|attempted|redelivery/i.test(latestEvent.description)) {
  estimate.earliest = addBusinessDays(now, 1); // Next business day retry
  estimate.latest = addBusinessDays(now, 3);
  estimate.note = 'Delivery was attempted. The carrier will retry.';
}

// failed, returned and lost mean it will not arrive without action
if (['failed', 'returned', 'lost'].includes(latestEvent.status)) {
  estimate.earliest = estimate.latest = null;
  estimate.note = 'This delivery needs attention. Contact support.';
}

Key Metrics to Track

Monitor these metrics to improve your estimation accuracy over time:

MetricTargetDescription
On-time accuracy> 85%Deliveries within estimated window
Average error< 1 dayMean absolute error in days
Customer inquiriesDecreasingWISMO calls related to delivery timing
Confidence calibrationAlignedHigh-confidence estimates should be right 95%+ of the time

Putting It All Together

Combining real-time tracking events with historical data gives you a powerful estimation system:

  1. Collect — Subscribe to tracking webhooks for all shipments
  2. Analyze — Process events and calculate estimates using status + historical data
  3. Display — Show estimates with appropriate confidence levels
  4. Learn — Record actual delivery times to improve future estimates
  5. Notify — Alert customers when estimates change significantly

By building this system on top of WhereParcel’s multi-carrier tracking API, you get consistent tracking events across 39+ live carriers, making it practical to build accurate estimates at global scale. Try it yourself in our interactive playground.

For more on setting up webhooks, see our Webhook Best Practices guide.

Can't find your carrier? We add new carriers on request — just let us know.

Request a carrier →

Got a question? Just ask. Drop by our Discord — the developer behind WhereParcel reads every message and replies personally. No bots, no tickets, just a real conversation.

Join Discord → Join Slack →

Tags: #delivery-estimates #tracking #ux #tutorial #customer-experience