sapient codelabs
AI development ·20 Jun 2026 ·5 min

How to Optimize Last-Mile Delivery Routes with OR-Tools and Python for Logistics Companies

Learn how to optimize last-mile delivery routes using OR-Tools and Python to reduce costs, improve efficiency, and enhance customer satisfaction.

Pranav Begade By Pranav Begade
How to Optimize Last-Mile Delivery Routes with OR-Tools and Python for Logistics Companies

Introduction to Last-Mile Delivery Optimization

Last-mile delivery represents the final and often most critical leg of the logistics journey, where packages travel from distribution centers to end customers. This phase accounts for up to 50% of total shipping costs and presents significant challenges for logistics companies striving to meet growing customer expectations for faster, more flexible deliveries.

In an era where same-day and next-day deliveries have become the norm, optimizing delivery routes has transformed from a nice-to-have optimization into a strategic imperative. Inefficient routes translate directly into higher fuel consumption, increased vehicle wear and tear, delayed deliveries, and dissatisfied customers. This is where mathematical optimization and powerful tools like Google's OR-Tools come into play.

OR-Tools is an open-source software suite designed for combinatorial optimization, with a particular emphasis on vehicle routing problems. When combined with Python's flexibility and extensive ecosystem, logistics companies can build sophisticated route optimization systems that dramatically improve operational efficiency. In this comprehensive guide, we'll explore how to leverage these powerful technologies to transform your delivery operations.

Understanding the Last-Mile Delivery Challenge

The last-mile delivery segment faces unique challenges that make route optimization particularly complex. Urban environments present congested traffic conditions, limited parking availability, and narrow streets that complicate navigation. Rural areas, conversely, involve long distances between delivery points, requiring careful balancing of route efficiency against coverage requirements.

Beyond geographical challenges, logistics companies must contend with time windows—customers often specify preferred delivery times, and businesses may require deliveries during specific operating hours. Multiple vehicle types with different capacities, driver shift restrictions, and the need to minimize empty miles all add layers of complexity to the routing problem.

Traditional route planning often relies on经验的启发式方法 or basic GPS navigation, which fails to account for the full picture of operational constraints. This approach typically results in suboptimal routes that waste resources and time. Mathematical optimization, particularly through the Vehicle Routing Problem (VRP) framework, enables companies to consider all relevant factors simultaneously and find truly optimal solutions.

Introduction to Vehicle Routing Problems and OR-Tools

The Vehicle Routing Problem (VRP) is a classic optimization challenge in operations research. At its core, VRP asks: given a fleet of vehicles stationed at a depot, a set of customers with specific demands, and various constraints, what is the most efficient set of routes to serve all customers? The classic formulation assumes vehicles start and end at the depot, must visit each customer exactly once, and cannot exceed their capacity.

Google's OR-Tools provides a powerful, well-documented library for solving VRP variants. The tool uses constraint programming and mixed-integer linear programming techniques to find optimal or near-optimal solutions to complex routing problems. OR-Tools supports numerous VRP extensions, including:

  • Capacitated VRP (CVRP): Vehicles have limited capacity constraints
  • VRP with Time Windows (VRPTW): Deliveries must occur within specified time intervals
  • VRP with Pickups and Deliveries (PDVRP): Vehicles transport goods between locations
  • Multiple Depot VRP: Vehicles can start from different locations
  • Period VRP: Deliveries are scheduled across multiple days

OR-Tools implements the VRP using a technique called local search with constraint programming, which proves highly effective for real-world routing problems. The solver iteratively improves solutions by making small modifications to routes while respecting all constraints, often finding excellent solutions within seconds even for large problem instances.

Setting Up Your Python Development Environment

Before diving into route optimization, you'll need to set up a Python environment with the necessary dependencies. Python 3.8 or later is recommended for compatibility with the latest OR-Tools features. The primary dependency is the OR-Tools package itself, which you can install via pip.

pip install ortools

OR-Tools depends on several underlying libraries, but the pip installation handles most dependencies automatically. For production environments, you may also want to install additional packages for data handling and visualization:

pip install pandas numpy matplotlib

Pandas provides powerful data manipulation capabilities for handling delivery data, NumPy offers numerical computing features, and Matplotlib enables visualization of optimized routes. These tools will prove valuable throughout the development and analysis phases of your routing system.

Building Your First VRP Solution with OR-Tools

Let's walk through creating a basic Capacitated Vehicle Routing Problem solver. We'll start with a simplified scenario: a single depot, multiple delivery locations with varying demand quantities, and a fleet of vehicles with limited capacity. This foundation will illustrate the core concepts before we add complexity.

The first step involves defining the data model. We need to specify the number of vehicles, their capacities, the locations of the depot and delivery points, and the quantity each customer requires. For demonstration purposes, we'll use synthetic data, but in production, this information would come from your order management system.

The core of any OR-Tools routing application involves three key components: the data manager, the routing index manager, and the routing model. The data manager holds your problem data, the index manager maps between internal indices and your location identifiers, and the model defines the optimization problem itself.

After setting up the model, we configure the search parameters. These parameters control how the solver explores the solution space, balancing solution quality against computation time. For production systems, you might want to set time limits, implement callback functions for progress monitoring, or customize the local search strategy.

The solver then attempts to find the optimal solution, and upon completion, we extract the routes and analyze the results. The output typically includes the total distance traveled, the number of routes required, and the specific sequence of stops for each vehicle.

Implementing Time Windows for Realistic Scenarios

Most real-world delivery scenarios require time windows—customers expect deliveries during specific time slots, and businesses have operating hours to consider. OR-Tools handles this elegantly through its time window constraints, which we can add to our basic VRP implementation.

To implement time windows, we need to define two parameters for each location: the earliest possible service time and the latest possible service time. The optimizer then considers these constraints when building routes, ensuring vehicles arrive within the specified windows.

When vehicles arrive early, they must wait until the time window opens—this is modeled as idle time in the optimization. Arriving late incurs penalties or makes the solution infeasible, depending on your configuration. The solver automatically balances these factors against route efficiency to find the best overall solution.

Advanced implementations might also incorporate service times—the duration required to complete delivery at each stop. This is particularly important for business deliveries that may involve significant unloading time or signature requirements. By accounting for service times, you ensure realistic arrival time calculations and better customer communication.

Advanced Optimization Techniques

Beyond basic VRP and time windows, several advanced techniques can further enhance your route optimization system. Distance matrices form the foundation of any routing calculation—these matrices store the travel time or distance between all pairs of locations. In production systems, you'll want to integrate with mapping APIs like Google Maps, OpenStreetMap, or HERE to obtain accurate, real-time distance data.

Traffic considerations add another layer of realism to your optimization. Time-dependent routing accounts for varying traffic conditions throughout the day, ensuring routes are optimized for actual travel times rather than average conditions. OR-Tools supports this through its dimension functionality, allowing you to model time as a cumulative resource that updates based on travel times between locations.

Multi-depot optimization becomes necessary when your operations span multiple distribution centers or warehouses. This variant allows vehicles to start and end their routes at different locations, which is common in regional logistics networks. The solver coordinates across all depots to minimize total system-wide costs.

Dynamic reoptimization addresses the reality that delivery plans often change throughout the day—new orders arrive, customers reschedule, or traffic disruptions require route changes. Implementing real-time optimization typically involves solving the routing problem periodically and adjusting current routes incrementally rather than completely replanning from scratch.

Real-World Implementation Considerations

Translating a proof-of-concept optimization model into a production system involves addressing several practical concerns. Data quality stands as perhaps the most critical factor—inaccurate addresses, missing customer information, or outdated distance calculations can significantly undermine optimization results. Investing in address validation and data hygiene processes pays dividends in solution quality.

Integration with existing systems presents another significant challenge. Your route optimizer must communicate with order management, warehouse management, driver mobile applications, and customer notification systems. Building robust APIs and data pipelines ensures information flows smoothly throughout your operations.

Driver considerations extend beyond vehicle capacity and time windows. Driver-specific constraints such as skill levels, familiar territories, break schedules, and overtime restrictions may impact route assignments. Some implementations incorporate driver preferences and performance history into the optimization algorithm.

Scalability becomes crucial as your operation grows. While OR-Tools can handle thousands of delivery points, computation time increases non-linearly with problem size. Techniques like clustering (dividing the problem into smaller geographic regions), hierarchical optimization, and incremental solving help maintain acceptable performance at scale.

Measuring and Improving Optimization Results

Implementing key performance indicators helps you understand the impact of route optimization on your operations. Primary metrics include total distance traveled, total delivery time, number of vehicles utilized, and percentage of deliveries completed on time. Comparing these metrics against pre-optimization baselines quantifies the return on your optimization investment.

Solution quality assessment should also consider robustness—how well do routes hold up when unexpected events occur? Highly optimized routes may become fragile when facing traffic or order changes, so building in some buffer time and flexibility often proves worthwhile.

Continuous improvement involves regularly revisiting your optimization parameters as conditions change. Customer expectations evolve, traffic patterns shift, and your fleet composition may change.定期重新校准优化模型确保您从投资中获得最大价值。

Conclusion

Route optimization through OR-Tools and Python represents a transformative capability for logistics companies seeking competitive advantage in last-mile delivery. By mathematically formulating routing decisions and leveraging powerful optimization algorithms, companies can achieve substantial cost reductions while improving service levels.

The journey from basic VRP implementations to fully integrated production systems requires thoughtful planning, quality data, and careful attention to operational constraints. However, the potential benefits—reduced fuel costs, improved delivery reliability, better asset utilization, and enhanced customer satisfaction—make this investment well worthwhile.

As e-commerce continues to accelerate and customer expectations intensify, efficient last-mile delivery becomes increasingly central to logistics success. Companies that master route optimization today position themselves to thrive in the demanding delivery landscape of tomorrow.

Frequently asked

1️⃣ What is OR-Tools and how does it help with route optimization?
OR-Tools is an open-source software suite developed by Google for solving combinatorial optimization problems, particularly vehicle routing problems. It uses constraint programming and mixed-integer linear programming techniques to find optimal or near-optimal routes for delivery fleets, considering constraints like vehicle capacity, time windows, and multiple depots.
2️⃣ Why is last-mile delivery optimization important for logistics companies?
Last-mile delivery accounts for up to 50% of total shipping costs and significantly impacts customer satisfaction. Optimizing routes reduces fuel consumption, vehicle wear, labor costs, and delivery times while improving service reliability. This efficiency gain translates directly to competitive advantage and improved profitability.
3️⃣ How do I implement time windows in OR-Tools route optimization?
To implement time windows in OR-Tools, you need to define earliest and latest service times for each delivery location. Use the AddTimeWindow method on locations in your routing model. The solver will then ensure vehicles arrive within specified windows, automatically handling wait times when vehicles arrive early.
4️⃣ What are the key benefits of using Python for logistics optimization?
Python offers several advantages for logistics optimization: extensive data handling libraries (Pandas), scientific computing (NumPy), visualization (Matplotlib), easy integration with existing systems, and a large ecosystem of machine learning and optimization tools. Its readability and rapid development capabilities make it ideal for prototyping and production deployment.
5️⃣ How do I get started with implementing route optimization in my company?
Start by collecting and cleaning your delivery data—addresses, time windows, package quantities, and vehicle information. Install OR-Tools via pip, begin with a basic CVRP implementation using the examples provided in the documentation, then progressively add complexity like time windows and multiple depots. Consider partnering with experienced developers if you need guidance for production systems.
Fixed price · $2,3002-week sprint

Building something in this space?

We turn ideas into buildable plans in 2 weeks — clickable prototype, technical plan, fixed quote. Fixed price, credited against the build.

See the Scoping Sprint

Contact Sapient Codelabs for expert route optimization development

Start a project →
Book a 15-min scoping call