Smart Dispatch and Cost Optimization for On-Demand Pet Supplies Delivery
On-demand pet supplies delivery lives or dies on unit economics: with low revenue per order, freight overruns erase margin quickly. This article breaks delivery cost into fixed trip cost, cost per kilometer, time-related cost, and auxiliary cost, models vehicle capacity as a dual volume-and-weight constraint, and applies a two-stage CVRPTW approach — order-to-vehicle assignment followed by insertion-based route improvement — to raise orders per trip. It also covers a layered system architecture with rolling-horizon re-planning, unified mileage and energy accounting with a SQL cost report and metrics dashboard, a simulation / canary / online-experiment validation loop, common pitfalls, and a five-phase rollout plan.
On-demand delivery of pet supplies (urgent runs, same-day delivery, store fulfillment) is hard not because the technology is trivial, but because its cost structure is extremely sensitive: revenue per order is low, and once freight costs slip out of control, the margin is gone. The complaints from the business side usually sound like “the drivers say there aren’t enough vehicles”, “operations says delivery is too expensive”, and “support says there are too many late deliveries”. Inside the system, these are different facets of the same problem: the lack of joint modeling of loading constraints, time-window constraints, and fixed trip costs.
The goal of this article is to turn these vague impressions into an engineering problem that can be modeled, optimized, and accounted for, and to lay out a practical implementation path.
1. Understand the Business Characteristics Before Optimizing
Pet supplies delivery has four characteristics that set it apart from ordinary food delivery and parcel express, and they directly determine the choice of algorithms and architecture.
1. Time-sensitive, but with a heavy handoff. Urgent orders usually have hard time windows, and delivery involves acceptance and confirmation of categories such as pet food and cat litter, so the variance in service time is far greater than in food delivery. If per-stop time is estimated with an average, the error gets amplified by the time windows into widespread lateness.
2. Loading constraints are volume-dominated. Dog food and cat litter are low-density, bulky items: the vehicle is full long before the weight limit is reached. The capacity model therefore has to be a dual constraint of weight plus volume; an implementation that models weight only will fail frequently in real dispatching.
3. Low value per order, so profit comes from consolidated orders. Orders per trip (the number of orders completed in a single dispatch) is one of the variables to which cost per order is most sensitive, so the first goal of route optimization should be to raise the effective load factor and orders per trip, not simply to cut kilometers.
4. Highly volatile demand. Morning and evening peaks, promotional events, and sudden restocking cause order density to swing several-fold, and static scheduling inevitably means a shortage of capacity at peaks and idle capacity in the troughs.
2. Get the Cost Model Right: Unit Economics
Optimization starts with measurement. It helps to break delivery cost into four parts: fixed trip cost + variable cost per kilometer + time-related cost + auxiliary cost.
- Fixed trip cost: the driver’s base hours for a dispatch, vehicle depreciation, insurance, and depot overhead allocation.
- Variable cost per kilometer: energy, maintenance, tires, and similar items.
- Time-related cost: late-delivery compensation, overtime, and cancellations caused by customers waiting.
- Auxiliary cost: loading, reverse logistics for returns, and exception handling.
This gives us cost per kilometer and cost per order:
C_km = energy_price × (kwh_per_100km / 100) + maint_per_kmC_trip = fixed_per_trip + C_km × mileage + time_penaltyC_order = C_trip / orders_per_tripProfitability condition: unit_price ≥ C_order
These formulas carry two engineering implications. First, orders_per_trip sits in the denominator, so the marginal return from raising orders per trip is usually higher than from pushing down cost per kilometer. Second, mileage and orders_per_trip are not independent: cutting empty running often raises orders per trip at the same time, which makes it the highest-priority optimization lever.
Sample implementation:
from dataclasses import dataclass@dataclass(frozen=True)class VehicleProfile:name: strfixed_per_trip: float # Fixed trip cost (labor + depreciation + depot allocation)energy_price: float # Energy unit price, CNY/kWh or CNY/Lconsume_per_100km: float # Measured consumption per 100 km (differs by vehicle type and season)maint_per_km: float # Maintenance cost amortized per kmvol_limit_m3: float # Volume limit: the dominant constraint for bulky categoriesweight_limit_kg: float # Weight limitavg_speed_kmh: float # Urban average speed, including stops and intersection waitingdef cost_per_km(p: VehicleProfile) -> float:return p.energy_price * p.consume_per_100km / 100.0 + p.maint_per_kmdef cost_per_order(p: VehicleProfile, mileage_km: float,orders_per_trip: int, penalty: float = 0.0) -> float:if orders_per_trip <= 0:return float("inf")trip = p.fixed_per_trip + cost_per_km(p) * mileage_km + penaltyreturn trip / orders_per_trip
On fleet selection, a few general rules have been repeatedly validated in the industry and can serve as modeling priors:
- Electric delivery vans have low energy cost per kilometer and few serviceable parts in urban low-speed, stop-and-go conditions, which suits high-frequency delivery with high daily mileage and relatively stable routes. The trade-off is that scheduling must incorporate battery constraints (SOC, usable range, charging windows, and depot charger slots), and usable range drops noticeably in cold weather.
- Fuel vans refuel flexibly and adapt better to intercity and long-haul scenarios, but their energy cost per kilometer is higher.
- Private passenger cars have limited cargo space, which easily forces order splitting and more trips, pushing up both time cost and cost per order.
The right approach is not to decide from experience, but to plug “daily mileage × cost per kilometer × operating days per month + trip cost” into one model and compare total cost of ownership and cost per order. Differences between vehicle types should be driven by a dim_vehicle configuration table rather than hardcoded in the logic.
3. Joint Optimization of Routing and Loading
Problem definition: this is a variant of the capacitated vehicle routing problem with time windows (CVRPTW) in which the capacity constraint extends to two dimensions, volume and weight. It must further support pickup from multiple warehouses or stores, a mixed fleet, and charging stops inserted for electric vehicles.
The objective function is best written as a weighted total cost, with the weights calibrated from historical data regression or business interviews:
minimize w1 × total mileage cost+ w2 × dispatch (trip) cost+ w3 × time-window violation penalty+ w4 × driver overtime hours+ w5 × number of route changes (re-planning churn penalty)
A two-stage solution strategy is recommended:
- Order-to-vehicle assignment. Cluster orders by geographic grid, time window, and category volume, then assign them to vehicle groups that can carry them, making sure first that everything fits and arrives on time.
- In-route sequencing. On the assigned set, build an initial solution with an insertion heuristic, then improve it iteratively with 2-opt, Or-opt, and large neighborhood search (ruin-and-recreate).
The skeleton of an insertion heuristic is below; the key point is that every insertion fully validates time windows, volume, weight, and (for electric vehicles) remaining range:
def best_insertion(route, order, dist, dur, veh, remaining_vol, remaining_kg):"""Pick the insertion position with the smallest cost delta across allfeasible positions in route; return None if no feasible position exists."""best, best_delta = None, float("inf")base = route_cost(route, dist) if route else 0.0for pos in range(len(route) + 1):cand = route[:pos] + [order] + route[pos:]if not feasible(cand, veh, remaining_vol, remaining_kg, dur):continuedelta = route_cost(cand, dist) - baseif delta < best_delta:best, best_delta = pos, deltareturn best, best_deltadef route_cost(route, dist):total, prev = 0.0, DEPOTfor node in route:total += dist[prev][node]prev = nodereturn total + dist[prev][DEPOT]
One engineering detail deserves special attention: re-planning churn. If rolling dispatch fully re-optimizes every round, drivers switch routes and orders change hands constantly, which noticeably hurts both the delivery experience and driver trust. In practice, suppressing churn with near-term time-slot locking plus a route-change penalty term is usually more valuable than chasing the global optimum.
4. Layered System Architecture
A split into four layers — access, capability, data, and observability — works well:
- Access layer: orders, store and product master data, and driver and vehicle profiles; it exposes unified APIs for placing orders and querying status.
- Capability layer:
- the order center, which owns the state machine and idempotent transitions;
- the fleet center, which manages driver shifts, vehicle capabilities (volume/weight/SOC), and depots;
- the dispatch engine, which runs clustering, assignment, and route optimization;
- the cost accounting service, which consolidates trip and mileage costs on a unified basis.
- Data layer: an online transactional store holds orders and trips, object storage holds large objects such as trajectory files and handoff photos, and a data warehouse holds offline analytics and simulation replay.
- Observability layer: logging, metrics monitoring, and alerting, covering key signals such as late-delivery rate, dispatch failure rate, and overload rate.
Three key design principles:
- Event-driven peak shaving. High-frequency events such as order status changes and driver position reports flow asynchronously through a message queue, with the dispatch engine and the accounting service consuming independently, so that an order peak does not crush the online path.
- Rolling-horizon re-planning. Re-plan incrementally for unfinished orders on a fixed cycle (for example, every 1–5 minutes). This naturally fits a stream of continuously arriving orders while keeping each solve within a size that completes in seconds.
- A replayable state machine. Every state transition must be reconstructable from the event log; otherwise production issues can neither be diagnosed nor rolled back.
If you build this system on a cloud platform such as Baidu AI Cloud, you can reuse general-purpose capabilities such as the container platform, object storage, message queue, logging, and monitoring/alerting, and focus your effort on the dispatch algorithms and business rules instead of rebuilding infrastructure.
5. Cost Accounting and Observability: Making Cost Visible Every Day
The payoff from cost optimization has to show up in reports. Start by standardizing three mileage definitions: onboard GPS trajectory mileage, vehicle odometer readings, and road-network estimated mileage. The differences usually come from detours, stop-point drift, and positioning drift; if left unmanaged, cost accounting becomes directly distorted. In practice, trajectory mileage is the primary definition, road-network estimates are used for up-front quoting and simulation, and odometer readings are used for periodic calibration.
Energy and fuel conversion should likewise be regressed per vehicle type and per season rather than using manufacturer nominal figures — urban conditions, load factor, and air-conditioning use all affect real values significantly.
WITH trip AS (SELECT t.stat_date, t.city, t.vehicle_id, t.vehicle_type,t.mileage_km, t.duration_min, t.order_cnt,v.cost_per_km * t.mileage_km + v.fixed_per_trip AS total_costFROM fact_trip tJOIN dim_vehicle v ON v.vehicle_id = t.vehicle_idWHERE t.stat_date >= CURRENT_DATE - INTERVAL '7' DAY)SELECT city,vehicle_type,SUM(total_cost) / SUM(order_cnt) AS cost_per_order,SUM(mileage_km) / SUM(order_cnt) AS km_per_order,SUM(order_cnt) / COUNT(DISTINCT vehicle_id || stat_date) AS orders_per_tripFROM tripGROUP BY city, vehicle_typeORDER BY cost_per_order DESC;
The core metrics dashboard should include cost per order, cost per kilometer, orders per trip, load factor (measured separately by volume and by weight), deadhead rate, on-time rate, orders per vehicle per day, and revenue per kilometer. Among these, load factor and orders per trip are the leading indicators that warn of cost deterioration earliest.
6. Closing the Loop: Simulation, Canary Releases, and Experiments
- Offline simulation replay. Replaying the historical order stream through the optimization engine and comparing total mileage, number of trips, on-time rate, and cost per order is the lowest-risk option before go-live.
- Canary rollout. Dispatch is a globally coupled system: one driver’s route affects other orders, so order-level random splitting easily contaminates the control group. Switch-based canaries by city, grid, or time slot are recommended.
- Online experiments. Use grids as the splitting unit, observe for at least one full weekly cycle, and also monitor counter-metrics: volatility in driver income per order, late-delivery complaint rate, and the share of exception orders. Any cost reduction accompanied by a large drop in driver income is unsustainable in the long run.
7. Common Pitfalls
- Optimizing mileage only and ignoring fixed trip cost, producing local optima and a higher total cost.
- A capacity model with weight only and no volume, making the plan infeasible in real dispatching.
- Estimating per-stop service time with an average. Handoff times for pet supplies vary widely, so use a quantile (such as P80) and keep a buffer.
- Electric fleet models that ignore range degradation and charging windows, creating a risk of mid-route charging in winter.
- Inconsistent mileage and energy definitions, so accounting results cannot be traced back to dispatch decisions.
- Re-planning with no change penalty, so drivers and orders change hands constantly and both experience and efficiency suffer.
- Exception flows (customer absent, refused delivery, reverse returns) left unmodeled and counted as normal trips, polluting the cost baseline.
8. Phased Rollout
- Phase 1: Connect order, vehicle, and driver master data, unify mileage and energy definitions, and establish a cost-per-order baseline.
- Phase 2: Launch rule-based dispatch plus mandatory loading validation (dual check on volume and weight), keeping infeasible plans out of the system from the start.
- Phase 3: Bring in the optimization engine and rolling re-planning, adding a change penalty and time-slot locking.
- Phase 4: Build the simulation-replay and canary-experiment capability, forming a “hypothesis → simulation → canary → full rollout” loop.
- Phase 5: Replicate across cities, bring the capacity pool, depots, and charging resources into unified elastic dispatch, and use demand forecasting to drive pre-scheduling.
9. Summary
The cost problem in urgent pet supplies delivery is essentially resource allocation under multiple constraints, not a vehicle-selection problem. Break cost per order into four measurable parts, describe loading with a dual-dimension capacity constraint, raise orders per trip with rolling-horizon optimization, and then guarantee that the optimization actually lands through unified accounting definitions and a simulation loop — done properly, these four things turn small reductions in cost per kilometer and small gains in orders per trip into stable profit at the mileage scale of high-frequency delivery. Conversely, any “optimization” that lacks loading validation, consistent accounting definitions, and experimental verification merely moves cost from one line item to another.
