# Route Optimization

The Route Optimization API solves traveling salesman and vehicle routing problems: given a set of stops to visit and a set of vehicles to visit them with, it returns an assignment of stops to vehicles and an order to visit them in, minimizing an objective you choose (total time, number of vehicles used, longest single route, etc.) while respecting constraints you specify (time windows, vehicle capacities, driver skills, and many more).

The [API reference](/openapi/route-optimization) has the request and response schema in detail. If you prefer to learn by example, jump to the [API Explorer](https://explorer.graphhopper.com/?endpoint=vrp) or the [Getting Started tutorial](https://www.graphhopper.com/blog/2019/05/17/getting-started-with-the-optimization-api-traveling-salesman-problem/).

## Mental Model

A request describes a **fleet**, a **workload**, and an **objective**. The API returns a **solution**.

The **fleet** is the set of vehicles that will execute the routes. Vehicles are described individually (start and end location, optional shift schedule); shared characteristics (routing profile, capacity, speed, cost per hour and per kilometer) are factored out into vehicle types.

The **workload** is the set of orders to be served. Each order is either a **service** (a single stop) or a **shipment** (a paired pickup and delivery that must end up on the same route, in order).

The **objective** is what the optimizer minimizes. Total time, number of vehicles used, longest single route, fairness across drivers. You choose, and you can combine multiple objectives in priority order.

A **solution** is a list of routes (one per used vehicle), each an ordered list of activities with arrival and departure times, plus an `unassigned` list for orders that could not be placed.

Two further mechanisms refine the model:

**Constraints** restrict which solutions are valid. Hard constraints (time windows, capacity, skills, allowed vehicles) leave non-conforming orders unassigned; soft constraints (priority, preferred vehicles) influence the optimizer without forbidding violations.

**Relations** link orders to each other beyond what an objective and constraints can express. They state that certain orders must be served on the same route, in a given sequence, or within a geographic flow, independently of what the optimizer would otherwise choose.

These five elements — fleet, workload, objective, constraints, relations — are everything you ever describe in a request.

## Minimal Example

A request with one vehicle, one vehicle type, four services, a relation, and an objective to minimize total time. One service exceeds the vehicle's capacity and will be left unassigned. The `in_direct_sequence` relation forces order-3 to be served immediately after the vehicle's start, followed immediately by order-2:

```json
{
  "vehicles": [
    {
      "vehicle_id": "driver-1",
      "type_id": "van",
      "start_address": { "location_id": "depot", "lon": 13.3888, "lat": 52.5170 },
      "earliest_start": 1746612000
    }
  ],
  "vehicle_types": [
    {
      "type_id": "van",
      "profile": "car",
      "capacity": [10]
    }
  ],
  "services": [
    {
      "id": "order-1",
      "address": { "location_id": "order-1", "lon": 13.3762, "lat": 52.5206 },
      "size": [2],
      "duration": 300,
      "time_windows": [{ "earliest": 1746612000, "latest": 1746615600 }]
    },
    {
      "id": "order-2",
      "address": { "location_id": "order-2", "lon": 13.4050, "lat": 52.5200 },
      "size": [3],
      "duration": 300
    },
    {
      "id": "order-3",
      "address": { "location_id": "order-3", "lon": 13.4270, "lat": 52.5230 },
      "size": [1],
      "duration": 300
    },
    {
      "id": "order-4",
      "address": { "location_id": "order-4", "lon": 13.395163, "lat": 52.526215 },
      "size": [20],
      "duration": 300
    }
  ],
  "objectives": [
    { "type": "min", "value": "completion_time" }
  ],
  "relations": [ { "type": "in_direct_sequence", "ids": ["start","order-3","order-2"] } ],
  "configuration": { "routing": { "calc_points": true } }
}
```

The response contains a `solution` with a `routes` array (one per used vehicle) and an `unassigned` object for orders that could not be placed:

```json
{
  "solution": {
    "distance": 10424,
    "transport_time": 1279,
    "completion_time": 2179,
    "no_vehicles": 1,
    "no_unassigned": 1,
    "routes": [
      {
        "vehicle_id": "driver-1",
        "points": [
          { "type": "LineString", "coordinates": [[13.3888,52.517],"...",  [13.427,52.523]] },
          { "type": "LineString", "coordinates": [[13.427,52.523], "...", [13.405,52.52]] },
          { "type": "LineString", "coordinates": [[13.405,52.52],  "...", [13.3762,52.5207]] },
          { "type": "LineString", "coordinates": [[13.3762,52.5207],"...",[13.3888,52.517]] }
        ],
        "activities": [
          { "type": "start", "location_id": "depot", "arr_time": 1746612000, "end_time": 1746612000, "load_after": [0] },
          { "type": "service", "id": "order-3", "location_id": "order-3", "arr_time": 1746612352, "end_time": 1746612652, "load_before": [0], "load_after": [1] },
          { "type": "service", "id": "order-2", "location_id": "order-2", "arr_time": 1746612966, "end_time": 1746613266, "load_before": [1], "load_after": [4] },
          { "type": "service", "id": "order-1", "location_id": "order-1", "arr_time": 1746613640, "end_time": 1746613940, "load_before": [4], "load_after": [6], "time_window": { "earliest": 1746612000, "latest": 1746615600 } },
          { "type": "end", "location_id": "depot", "arr_time": 1746614179, "end_time": 1746614179, "load_before": [6] }
        ]
      }
    ],
    "unassigned": {
      "services": ["order-4"],
      "details": [{ "id": "order-4", "code": 3, "reason": "does not fit into any vehicle due to capacity" }]
    }
  }
}
```

Note that `time_windows` use Unix timestamps (recommended). The `in_direct_sequence` relation forced the solver to visit order-3 then order-2 immediately after the start, even though a different sequence might have been shorter. `order-4` was left unassigned with reason code 3 (capacity exceeded: size 20 vs. vehicle capacity 10). Because `configuration.routing.calc_points` is `true`, the response includes a `points` array with one LineString geometry per leg — use these to render routes on a map without a separate Routing API call.

## Concepts

### Services vs. Shipments

The choice matters because it changes what the optimizer is allowed to do.

A **service** is loaded onto the vehicle for the rest of the route (if `type` is `service` or `pickup`) or treated as already-loaded at the depot and dropped at the customer (`type: delivery`). The optimizer is free to interleave services from different customers in any order that satisfies constraints.

A **shipment** introduces an ordering constraint: the pickup of shipment X must happen before the delivery of shipment X, on the same route. Between those two stops, the optimizer can interleave other services or other shipments' pickups and deliveries, as long as capacity holds.

Use services for typical last-mile delivery (where goods come from a single depot), customer visits, technician dispatch. Use shipments when goods move directly between customer locations: courier work, ride-hailing, moving services, vehicle repositioning.

### Constraints: Hard vs. Soft

Constraints fall into two categories, and understanding the difference is critical for diagnosing why the solver returned the result it did.

**Hard constraints** must be satisfied. If they cannot be, the order is left unassigned and appears in `solution.unassigned`. Hard constraints include:

- Time windows on services, shipments, and vehicle shifts (a time window can be made partially soft with `max_lateness`, see [Soft Time Windows](#soft-time-windows-beta))
- Vehicle capacity vs. order size
- Skills (a service's `required_skills` must be a subset of the assigned vehicle's `skills`)
- `allowed_vehicles` and `disallowed_vehicles` lists
- `max_distance`, `max_driving_time`, `max_service_time`, `max_working_time`, `max_route_duration`, `max_jobs`, `max_activities` per vehicle
- `max_time_in_vehicle` for deliveries
- Relation constraints (`in_sequence`, `in_direct_sequence`, `in_same_route`, `in_area_sequence`)


**Soft constraints** influence the solution but do not prevent assignment. Violating them costs the optimizer *score*, so it tries to avoid them, but will accept a violation if there's no alternative. Soft constraints include:

- `priority` on services and shipments (high-priority orders get assigned first when not all can be served)
- `preferred_vehicles`
- `min_jobs` per vehicle


When an order ends up unassigned, the response includes `solution.unassigned.details` with a code indicating the most likely reason (capacity, time window, skill mismatch, etc.) and a `reasons` array with all probable causes ranked by likelihood. The full code table is in the [POST /vrp reference](/openapi/route-optimization/solvevrp).

#### Soft Time Windows (Beta)

A time window is hard by default: an order that cannot start between `earliest` and `latest` is left unassigned. In practice many deadlines are not that strict. A pharmacy would rather receive its delivery ten minutes after closing of the agreed slot than not at all, and a dispatcher would rather accept five minutes of lateness at one stop than send the vehicle on a twenty-minute detour. `max_lateness` expresses exactly that:

```json
"time_windows": [
  { "earliest": 28800, "latest": 36000, "max_lateness": 900 }
]
```

This keeps `earliest` to `latest` as the **preferred range**, in which starting the activity is free, and allows a start of up to `max_lateness` seconds after `latest` at a penalty that grows with every second of lateness. `latest + max_lateness` remains a **hard limit**: beyond it the order is left unassigned as before. `earliest` stays hard, too; a vehicle that arrives early waits.

The optimizer uses the allowance only when it pays off: when lateness rescues an order that would otherwise be unassigned, or when a small lateness avoids a clearly longer route. Punctual solutions are always preferred over late ones, and late ones over unassigned orders. Lateness is priced linearly, so two stops that are five minutes late cost the same as one stop that is ten minutes late. If you need a tighter guarantee for a particular customer, lower that customer's `max_lateness`; it is set per time window, so every order and every window can carry its own allowance, on services as well as on the pickups and deliveries of shipments.

The response reports what happened: every activity carries `late_by`, the seconds its start lies after `latest` (0 when punctual), and each route as well as the solution carry `lateness` (the sum of `late_by`) and `late_activities` (the number of late stops).

Two things to keep in mind. First, all unassigned orders cost the same unless you say otherwise, so the optimizer may drop an order with a hard window to rescue two orders with soft windows; give important hard-window orders a high `priority`. Second, if an activity has several time windows, their hard ends (`latest + max_lateness`) must be distinct.

### Relations: Shaping the Solution

The objectives plus hard and soft constraints can express most of what a router needs, but not everything. Real-world dispatchers carry knowledge that resists formalization: a driver prefers to clear the north side of town before lunch, two stops at the same office should be done back-to-back so the driver only signs in once, a particular customer expects to be the first visit of the day, the morning route should sweep west-to-east before circling back. These aren't gaps in the API — they're the gap between any abstract objective and the messy reality of operations. Drivers have preferences, customers have habits, and dispatchers have judgment that earned its keep over years.

**Relations are the escape hatch for that gap.** Instead of trying to encode every preference as an objective or constraint, you let the optimizer do its job within boundaries you define. A relation says "whatever else you decide, this constraint must hold."

The available relation types:

- **`in_same_route`** — the related items must end up on the same vehicle, regardless of order.
- **`not_in_same_route`** — the related items must end up on different vehicles. This is the only exclusion relation; all others pull items together.
- **`in_sequence`** — the related items must appear in the listed order on a single route, but other stops may be inserted between them.
- **`in_direct_sequence`** — the related items must appear in the listed order on a single route, with no stops in between.
- **`neighbor`** — the related items must be served by the same vehicle and appear next to each other, but in any order.
- **`in_area_sequence`** — each area is defined by an anchor stop and a radius; all stops within that radius belong to the area. The areas must be visited in the given order, while the optimizer remains free to sequence stops within each area.


`in_area_sequence` is unique among the six in that the grouping is defined spatially, by an anchor stop and a radius, rather than by labels you assign to individual orders. A dispatcher picks a few anchor stops, sets a radius for each, orders the resulting areas, and the optimizer respects the geographic flow while still finding the best sequence within each area. The dispatcher's tacit knowledge about traffic, neighborhood characteristics, or driver preference becomes a few clicks; the optimizer handles the rest.

#### Two Granularities: Orders and Groups

Relations operate at two granularities, depending on which field you populate.

**Order-level relations** use the `ids` field, listing individual service or shipment ids. `in_sequence` over `["service-A", "service-B"]` means service-A must be served before service-B on the same route.

**Group-level relations** use the `group` field, listing group labels instead of order ids. `in_sequence` over groups `["downtown", "uptown"]` is a higher-order constraint: every stop tagged `group: "downtown"` must be served before every stop tagged `group: "uptown"`. The relation operates on the clusters as units, not on the individual stops inside them.

Group-level relations are what make interactive UIs practical. A dispatcher assigns a group label to a set of stops in a neighborhood, and a single relation entry sequences that group against another, regardless of how many stops are inside either one. The dispatcher works with a handful of meaningful clusters; the request stays compact regardless of how many orders the underlying problem contains.

#### Groups Own Semantics

Groups are not only labels you reference from relations. Assigning the same group label to two or more orders is itself a constraint.

Tagging orders with the same group does two things at once. First, it treats them as a contiguous cluster: wherever they are served, they appear as a block, with no other stops inserted between them. Second, it leaves the order within that block to the optimizer. A group is in effect a "weak in_sequence": the stops stay together, but the algorithm picks the best internal sequence.

The cluster constraint is about contiguity, not route assignment. In a multi-vehicle problem, the orders in group A and the orders in group B can land on different routes; the optimizer is free to make that choice. On each route a group appears on, its members are contiguous. If you want all members of a group on the same route, add an `in_same_route` relation over the group, or pin the group to a specific vehicle by adding a `vehicle_id` to the relation.

Ungrouped orders are by default not allowed to be inserted inside a group; if you need that flexibility, set `configuration.optimization.free_insertion` to true. You can then exempt specific groups (typically conventional ones like `"asap"` or `"last"`) from free insertion via `free_insertion_exempt_groups`, so those groups remain compact while other ungrouped orders move freely.

#### Practical Notes

Relations are hard constraints: an order in an unsatisfiable relation appears in `unassigned` with reason code 21 (or 29 for group constraints). They compose with all other constraints, so a relation that conflicts with a time window or capacity will leave the affected orders unassigned.

Relations can also be built dynamically. A common pattern is to take the result of a first optimization, extract the sequence the optimizer chose, and feed it back as `in_direct_sequence` relations to lock that sequence in for the next request. This is useful when re-planning around late-breaking changes without disrupting an already-communicated route. Watch for cases where the new constraints over-constrain the problem and previously-assignable orders become unassigned.

### Choosing an Objective

Pick the objective that matches what you're actually optimizing for. The defaults that suit most use cases:

**Just minimize total time:** `min completion_time`. This is the right answer for ~80% of real dispatch problems.

**Use as few vehicles as possible, then minimize time:** combine `min vehicles` followed by `min completion_time`. The order matters: the optimizer treats objectives lexicographically, so vehicles are minimized first, completion time second.

**Finish all routes as early as possible (minimize the longest route):** `min-max completion_time`. Useful when you have a hard end-of-day deadline and want all drivers home around the same time.

**Distribute work fairly across drivers:** `balance completion_time` (Beta) or `balance activities`. The `balance` type minimizes the variance of workload, while `min-max` only minimizes the longest route. Use `balance` when fairness matters; use `min-max` when only the latest finish time matters.

**Travel time only, ignoring waiting at customer sites:** `min transport_time`. Rare. Most users actually want `completion_time`.

For a deeper discussion, see [completion time vs. transport time](https://www.graphhopper.com/blog/2016/06/20/what-is-the-difference-between-the-minimization-of-completion-time-and-minimizing-transport-time/).

### Modeling Time at a Stop

Every stop has a timeline the optimizer tracks: arrival, preparation, waiting, setup, service, departure. Getting this right matters because it determines when time windows are evaluated, how long a vehicle stays, and ultimately what the optimizer can fit into a route.

Three parameters control how long a vehicle spends at a stop, and they differ in *when* they apply and *how often* they are charged:

- **`duration`** is the actual service time — loading, unloading, performing a task. It is charged for every activity, so two deliveries at the same warehouse each add their own duration.
- **`preparation_time`** is time spent after arrival but before the time window is evaluated — finding a parking spot, walking from the truck to the entrance. It is charged once per location: if the vehicle serves multiple orders at the same address consecutively, preparation happens only on the first.
- **`setup_time`** is fixed overhead that happens after the time window opens but before service begins — dock check-in, security clearance, equipment setup. Like preparation time, it is charged once per location.


The full sequence is: `arrival → preparation_time → waiting (if early) → setup_time → duration → departure`. A **time window** defines when an activity can *start* — the vehicle must begin service between `earliest` and `latest`. It does not require the activity to finish within the window; a service that starts at `latest` and runs for its full duration will end after the window closes, and that is valid. A vehicle that arrives before `earliest` waits (after preparation) until the window opens, then starts setup, then performs the service. With `max_lateness` on the window, the start may also fall up to that many seconds after `latest`, at a penalty; see *Soft Time Windows* under *Constraints: Hard vs. Soft* above.

Most problems only need `duration`. Add `preparation_time` when vehicles consistently lose time reaching the actual service point (urban deliveries with scarce parking, large campus sites). Add `setup_time` when certain locations impose a fixed entry overhead regardless of how many tasks you perform there. If you are unsure, start with `duration` alone — the other two are refinements, not requirements.

For a detailed walkthrough with a timeline diagram and comparison table, see [Stop Timing: preparation, setup and duration](https://www.graphhopper.com/blog/2026/05/27/stop-timing-preparation-setup-and-duration/).

### Synchronous vs. Asynchronous

Two endpoints solve the same problem with different delivery mechanisms.

**`POST /vrp`** (synchronous) returns the solution in the response body. Use this when the problem is small enough to solve in under 10 seconds. If the solver runs longer, the request times out and you lose the work.

**`POST /vrp/optimize`** (asynchronous) returns a `job_id` immediately. You then poll **`GET /vrp/solution/{jobId}`** every 500ms or so until `status` is `finished`. Use this for any problem that might exceed 10 seconds.

As a rule of thumb, prefer the synchronous endpoint for problems with a single vehicle and up to 200 stops. If you're unsure, start synchronous; if you hit timeouts, switch to async. The async workflow has the same request body, so switching is a one-line change.

### Endpoints

- [POST /vrp](/openapi/route-optimization/solvevrp): synchronous endpoint. Returns the solution in the response. Suitable for problems that solve in under 10 seconds.
- [POST /vrp/optimize](/openapi/route-optimization/asyncvrp): asynchronous endpoint. Returns a `job_id`; fetch the solution from the endpoint below. Use this for problems that take longer than 10 seconds. The request body is identical to `/vrp`.
- [GET /vrp/solution/{jobId}](/openapi/route-optimization/getsolution): poll this endpoint until `status` is `finished`. Recommended interval: 500ms.


### Further reading

- [Getting Started with the Optimization API](https://www.graphhopper.com/blog/2019/05/17/getting-started-with-the-optimization-api-traveling-salesman-problem/) — step-by-step walkthrough of a first VRP request
- [Area Sequencing: shape your routes by area](https://www.graphhopper.com/blog/2026/05/04/area-sequencing-shape-your-routes-by-area/) — using `in_area_sequence` to control geographic flow
- [Solving a TSP with a week-planning horizon and driver shifts](https://www.graphhopper.com/blog/2020/07/15/how-to-solve-a-traveling-salesman-problem-with-a-week-planning-horizon-and-driver-shifts/)
- [Scheduling technicians with skills and multiple dependencies](https://www.graphhopper.com/blog/2016/06/03/how-to-route-technicians-with-skills-and-multiple-dependencies-between-tasks/)
- [Completion time vs. transport time](https://www.graphhopper.com/blog/2016/06/20/what-is-the-difference-between-the-minimization-of-completion-time-and-minimizing-transport-time/)
- [Modeling multi-trip routes for a single vehicle](https://www.graphhopper.com/blog/2016/07/21/how-to-model-multiple-delivery-routes-with-a-single-vehicle/)