Route Optimization: Solving Vehicle Routing With Time Windows in Spring Boot and Timefold

8:00 a.m. One vehicle at the depot, 14 deliveries in the driver's hands. Five of them have time windows: one customer wants to receive their delivery between 8:30 and 9:30, another won't be home before 11:00. The dispatcher's mental rule is simple: "go to the nearest address." In this post, we planned these 14 stops with four different methods and calculated the results down to the minute. The resulting table shows why route optimization isn't a "find the shortest path" job.

In short: the pure "nearest stop" rule is late for 6 customers. Switching to the "nearest stop that's open right now" rule to avoid being late brings lateness down to zero, but the distance climbs to 65.5 km. A constraint solver finishes the same job in 41.6 km with zero lateness. Below, we explain how that works, how to set it up with Timefold on Spring Boot, and what actually breaks things in the field.

The Same 14 Stops, Three Separate Plans

We kept the example reproducible: a 10 x 10 km area, the depot in the middle, a road factor of 1.3 on straight-line distance, an average speed of 30 km/h, and 6 minutes of delivery time at each stop. A vehicle that arrives early at a stop with a time window waits at the door. A stop reached after its window closes counts as "late." Here are the results of the four methods:

MethodDistanceLate stopsDay ends
Go to the nearest stop45.4 km6 (889 min total)14:06
Go to the nearest stop that's open right now65.5 km011:42
Minimize mileage only40.3 km6 (855 min total)13:56
Constraint solver41.6 km012:23

The first row shows why the rule is dangerous. In the morning, the vehicle goes to the nearest address, waits at the door because that address's window doesn't open until 11:30, and misses every one of the morning appointments. The second row is the fix a sensible dispatcher would make: skip any address whose window isn't open. Lateness disappears, but the vehicle shuttles back and forth from one end of the city to the other.

The real lesson is in the third row. When we try to minimize mileage alone, the shortest route we find is 40.3 km, and it's still late for 6 customers. The solver's plan, by contrast, is only 1.3 km longer and keeps no one waiting. In route optimization, constraints come before distance.

The same 14 stops planned with three different methods; as the clock advances, the vehicles follow their routes and late stops turn red
All three plans set out at the same time. Stops with orange rings are deliveries that have a time window.

Why Is the Problem So Hard?

In academia, this problem is called the Vehicle Routing Problem with Time Windows, or VRPTW for short. Because it's a generalization of the traveling salesman problem, it's NP-hard: as the number of stops grows, the number of possible orderings grows factorially. 14 stops have 14! = 87,178,291,200 different orderings. At 20 stops, that number rises to about 2.4 x 1018. Once you add the number of vehicles, capacity, and driver working hours, trying every possibility one by one becomes impossible for a real fleet.

For small instances, there are mathematical programming methods that give exact solutions. In the field, though, the accepted approach is different: build a reasonable starting plan and improve it step by step within a limited time. It's a method that's reliably good but doesn't prove optimality. It's also an "anytime" method: stop it at 5 seconds and you get a good plan; stop it at 60 seconds and you get a better one.

Mandatory Rules and Preferred Rules

We don't tell the solver "find the shortest route." We give it the rules and the weight of each rule. The rules fall into two classes:

  • Mandatory (hard) rules: vehicle capacity is never exceeded, a delivery window is never missed, driver working hours are never exceeded. A plan that violates any of these is a bad plan, whatever its mileage.
  • Preferred (soft) rules: less driving, less waiting at the door, the same driver in the same area where possible. These are used to choose between plans.

The score is kept in two parts, for example 0hard/-2.430soft. The hard part is compared first; the soft part only comes into play if the hard parts are equal. That's why 1 minute of lateness counts as worse than 100 km of extra distance. It's also why the solver didn't pick the "shortest" route in the table.

The soft weights, on the other hand, are a business decision. In our example, we counted one minute of driving as 6 times as expensive as one minute of waiting at the door. That's why the solver was willing to wait until 9:00 at the first stop in exchange for shortening the total distance. When we tripled the weight we gave to time, the solver found a different plan that ends at 11:50 but covers 52.6 km. Both are correct answers; which one is "good" is decided by driver costs and customer contracts, not by the algorithm.

How Does the Solver Search?

The search proceeds in two phases. First, a starting plan is built; most solvers do this with a fast heuristic, placing each stop wherever it does the least damage at that moment. Then local search begins: a small change is made to the plan, the score is recalculated, and the change is either accepted or undone. Typical changes include:

  • Moving a stop to a different position in the route.
  • Swapping the positions of two stops.
  • Reversing a section of the route (2-opt). This untangles two crossing route lines.
  • In a multi-vehicle problem, assigning a stop to a different vehicle.

A search that only accepts improving changes gets stuck on the first local peak. That's why methods that occasionally allow worsening changes are used: simulated annealing, late acceptance, and tabu search are the best known.

The animation below shows real intermediate results we recorded while solving our example with a small simulated annealing run. We gave the solver the "nearest stop" plan as its starting plan. The 889 minutes of lateness dropped to zero within the first 70 attempts. The remaining attempts improved only the soft part, that is, mileage and waiting.

Every better route the solver finds during the search; lateness drops to zero first, then the distance gets shorter
Each frame is the best route the search has found up to that point. The mandatory rule first, then distance.

Setting It Up With Spring Boot and Timefold

In the Java world, two mature options stand out for this job. Google OR-Tools is a powerful routing library written in C++ that offers bindings for many languages, including Java. Timefold Solver (a project continued by the team that developed OptaPlanner) runs entirely in Java and lets you write the rules directly in Java code. For a team using Spring Boot, the second path means less friction. The examples below were written with Timefold Solver 2.8.0, which was current when this post was published. Let's note up front that the official Spring Boot starter supports only Spring Boot 4.x versions.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>ai.timefold.solver</groupId>
      <artifactId>timefold-solver-bom</artifactId>
      <version>2.8.0</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>ai.timefold.solver</groupId>
    <artifactId>timefold-solver-spring-boot-starter</artifactId>
  </dependency>
</dependencies>

The Model: A Vehicle Is a List, a Stop Is an Element of That List

The right modeling tool for routing is the "list variable." The solver arranges each vehicle's list of stops; which vehicle a stop belongs to, the stop before it, and its arrival time are shadow variables derived automatically from that list.

@PlanningEntity
public class Vehicle {

    @PlanningId
    private String id;
    private int capacity;
    private Location depot;
    private LocalDateTime departureTime;

    @PlanningListVariable
    private List<Visit> visits = new ArrayList<>();

    public int getTotalDemand() {
        return visits.stream().mapToInt(Visit::getDemand).sum();
    }

    public long getTotalDrivingTimeSeconds() {
        long total = 0;
        Location previous = depot;
        for (Visit visit : visits) {
            total += previous.drivingSecondsTo(visit.getLocation());
            previous = visit.getLocation();
        }
        return visits.isEmpty() ? 0 : total + previous.drivingSecondsTo(depot);
    }
}
@PlanningEntity
public class Visit {

    @PlanningId
    private String id;
    private Location location;
    private int demand;
    private LocalDateTime windowStart;
    private LocalDateTime windowEnd;
    private Duration serviceDuration;

    @InverseRelationShadowVariable(sourceVariableName = "visits")
    private Vehicle vehicle;

    @PreviousElementShadowVariable(sourceVariableName = "visits")
    private Visit previousVisit;

    @CascadingUpdateShadowVariable(targetMethodName = "updateArrivalTime")
    private LocalDateTime arrivalTime;

    private void updateArrivalTime() {
        if (previousVisit == null && vehicle == null) {
            arrivalTime = null;
            return;
        }
        LocalDateTime leaving = previousVisit == null
                ? vehicle.getDepartureTime()
                : previousVisit.getDepartureTime();
        Location from = previousVisit == null ? vehicle.getDepot() : previousVisit.getLocation();
        arrivalTime = leaving == null ? null : leaving.plusSeconds(from.drivingSecondsTo(location));
    }

    public LocalDateTime getServiceStart() {
        if (arrivalTime == null) {
            return null;
        }
        return arrivalTime.isBefore(windowStart) ? windowStart : arrivalTime;
    }

    public LocalDateTime getDepartureTime() {
        LocalDateTime start = getServiceStart();
        return start == null ? null : start.plus(serviceDuration);
    }

    public long getLateMinutes() {
        LocalDateTime start = getServiceStart();
        return start == null || !start.isAfter(windowEnd) ? 0 : Duration.between(windowEnd, start).toMinutes();
    }

    public long getWaitMinutes() {
        return arrivalTime == null || !arrivalTime.isBefore(windowStart) ? 0 : Duration.between(arrivalTime, windowStart).toMinutes();
    }
}

The critical piece here is @CascadingUpdateShadowVariable. When the solver moves a stop in the list, only the arrival times of the affected stops are recalculated; the entire route isn't recalculated from scratch. Being able to try tens of thousands of changes per second depends on this incremental calculation.

The Rules: Plain Java Code

public class RoutingConstraints implements ConstraintProvider {

    @Override
    public Constraint[] defineConstraints(ConstraintFactory factory) {
        return new Constraint[] {
                vehicleCapacity(factory),
                lateService(factory),
                drivingTime(factory),
                waitingAtDoor(factory)
        };
    }

    Constraint vehicleCapacity(ConstraintFactory factory) {
        return factory.forEach(Vehicle.class)
                .filter(vehicle -> vehicle.getTotalDemand() > vehicle.getCapacity())
                .penalizeLong(HardSoftScore.ONE_HARD,
                        vehicle -> vehicle.getTotalDemand() - vehicle.getCapacity())
                .asConstraint("Vehicle capacity");
    }

    Constraint lateService(ConstraintFactory factory) {
        return factory.forEach(Visit.class)
                .filter(visit -> visit.getLateMinutes() > 0)
                .penalizeLong(HardSoftScore.ONE_HARD, Visit::getLateMinutes)
                .asConstraint("Delivery window");
    }

    Constraint drivingTime(ConstraintFactory factory) {
        return factory.forEach(Vehicle.class)
                .penalizeLong(HardSoftScore.ONE_SOFT, Vehicle::getTotalDrivingTimeSeconds)
                .asConstraint("Driving time");
    }

    Constraint waitingAtDoor(ConstraintFactory factory) {
        return factory.forEach(Visit.class)
                .filter(visit -> visit.getWaitMinutes() > 0)
                .penalizeLong(HardSoftScore.ONE_SOFT, visit -> visit.getWaitMinutes() * 10)
                .asConstraint("Waiting at door");
    }
}

Driving costs 1 point per second, and waiting costs 10 points per minute. One minute of driving is worth 60 points and one minute of waiting is worth 10; that's the 6-to-1 ratio we described above. Reading the weights from configuration instead of hard-coding them lets the dispatcher say "waiting is expensive today."

Running the Solver

Planning shouldn't happen inside an HTTP request; a 30-second search will hit the request timeout. That's why the Spring Boot starter provides a SolverManager that runs solves in a separate thread pool.

timefold.solver.termination.spent-limit=30s
timefold.solver.termination.unimproved-spent-limit=5s
@Service
public class RoutePlanningService {

    private final SolverManager<RoutePlan, String> solverManager;

    public RoutePlanningService(SolverManager<RoutePlan, String> solverManager) {
        this.solverManager = solverManager;
    }

    public RoutePlan plan(String jobId, RoutePlan problem) throws InterruptedException, ExecutionException {
        SolverJob<RoutePlan, String> job = solverManager.solve(jobId, problem);
        return job.getFinalBestSolution();
    }
}

The unimproved-spent-limit setting ends the search without waiting for the full 30 seconds if the score hasn't improved for 5 seconds. It's the practical way to get the plan quickly on light days while keeping the time bounded on heavy days.

Four Things That Break It in the Field

Everything up to this point is also in the libraries' documentation. The real difficulty starts with how accurately the model reflects the real world.

1. The Distance Matrix Can't Be Straight-Line

In our example, for simplicity, we scaled up straight-line distance by a factor. In a real system, that's unacceptable. Because of one-way streets, bridges, and turn restrictions, the distance from A to B differs from the distance from B to A; in other words, the matrix is asymmetric. This matrix should come from a road network engine such as OSRM, GraphHopper, or Valhalla. OSRM's table service returns a table of durations and distances between many points in a single request.

The second problem is size. The matrix grows with the square of the number of stops: 2,000 stops means 4 million cells. If you store duration and distance as 8-byte numbers, that comes to 64 MB for a single set of matrices. Add separate time slices for morning and evening traffic on top of that, and generating, caching, and updating the matrix becomes an infrastructure job in its own right.

On a grid of one-way streets, the straight-line distance between A and B, the outbound route, and the longer return route
Illustrative street grid. Straight-line 1.5 km, outbound 2.1 km, return 2.7 km.

2. Delivery Time Is Often Longer Than Driving Time

The "6 minutes at every stop" assumption in the model is the number that's most often wrong in urban delivery. Looking for parking, getting through the security gate of a residential complex, climbing to the fifth floor of a building without an elevator: these multiply that time. If plans hold up on paper but keep slipping in the field, this is the first place to look.

This duration shouldn't be estimated; it should be measured. Vehicle tracking data is enough for this: the time during which the vehicle's speed stays near zero close to a delivery address is that address's real delivery time. Grouping these durations by address type, time of day, and area, and feeding them into the model as medians and percentiles rather than averages, is the step that does the most to close the gap between plan and reality.

3. The Plan Is Made in the Morning, the Day Changes at Noon

At 10:00, a new urgent order comes in: it needs to be delivered between 10:30 and 11:15. The easiest option is to add it to the end of the route. In our example, that means being 76 minutes late for the new order. When we replan the remaining stops, lateness drops to zero; in exchange, the distance rises from 49.0 km to 52.4 km and the day ends 20 minutes earlier.

Two details matter here. First, stops that are completed or currently in progress must not be moved during replanning. In Timefold, this is done with @PlanningPinToIndex, which pins the first N elements of the list variable. Second, instead of stopping the solver and starting over, add the change to the running solve: using SolverManager.addProblemChange to send a ProblemChange brings the new order into the search without losing the current best plan.

public record AddVisit(Visit visit) implements ProblemChange<RoutePlan> {

    @Override
    public void doChange(RoutePlan plan, ProblemChangeDirector director) {
        director.addEntity(visit, plan.getVisits()::add);
    }
}

solverManager.addProblemChange(jobId, new AddVisit(urgentVisit));

The number of pinned elements must not change during the search; when the vehicle completes a stop, incrementing that number should also be done through a ProblemChange. When this rule, which the documentation explicitly emphasizes, is violated, score calculation breaks and tracking down the source of the error becomes very hard.

A new order arrives at 10:00; the six completed stops stay locked while the remaining route is replanned
Completed stops stay locked; only the remaining route is replanned.

4. If the Dispatcher Doesn't Trust It, the Plan Gets Overridden by Hand

Even the best plan gets changed by hand in the field if it can't answer the question "why this order?" This is where the benefit of keeping rules named shows up: you can display a breakdown next to each plan, such as "delivery window: 0, driving: 41.6 km, waiting at the door: 96 min." Timefold offers an analysis interface (SolutionManager) that provides a per-rule score breakdown for this; since some analysis features are in the paid edition, we recommend checking the documentation for what the edition you use covers. Instantly showing how much a dispatcher's manual change worsens the score also builds trust quickly.

When Don't You Need a Solver?

Not every delivery operation needs this level of complexity. With one or two vehicles, around ten stops a day, and deliveries without time windows, a simple rule followed by a 2-opt cleanup pass is often enough. A solver pays for itself when the number of vehicles grows, when time windows and capacity come into play together, and when the plan changes during the day. The 24 km daily difference in our example is for a single vehicle on a single day; as the fleet grows, that difference feeds directly into fuel, working hours, and customer satisfaction.

In courier and vehicle tracking systems, designing route optimization as a separate module, that is, keeping matrix generation, the solver, and feedback from the field separate from one another, is the architectural decision that makes scaling the system easiest. On our courier and delivery software page, we describe the overall structure of this module.

Sources

  • Timefold Solver documentation: docs.timefold.ai (sections on list variables, shadow variables, pinning, and real-time planning)
  • Google OR-Tools, vehicle routing guide: developers.google.com/optimization/routing
  • OSRM API documentation, table service: project-osrm.org
  • M. M. Solomon, "Algorithms for the Vehicle Routing and Scheduling Problems with Time Window Constraints", Operations Research 35(2), 1987.
  • P. Toth, D. Vigo (eds.), Vehicle Routing: Problems, Methods, and Applications, 2nd ed., SIAM, 2014.

Note: The sample data in this post is synthetic; the figures were calculated for this example and do not represent any real customer operation.

Cover photo: STILL_PHOTOGRAPHY / Pixabay