> ## Documentation Index
> Fetch the complete documentation index at: https://docs.solvice.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Real-Time Scheduling

> Implement dynamic schedule adjustments throughout the day by combining initial bulk optimization with rapid real-time updates

# Real-Time Scheduling

Real-time scheduling enables you to maintain optimal routes throughout the day by combining comprehensive morning planning with rapid on-the-fly adjustments. This two-phase approach handles both strategic daily planning and tactical real-time responses to changing conditions.

## How Real-Time Scheduling Works

Real-time scheduling leverages two different solve endpoints to balance comprehensive optimization with speed:

```mermaid theme={null}
flowchart LR
    subgraph "Morning Planning"
        A["Morning: 200+ Jobs"]
        B["/v2/vrp/solve"]
        C["Complete Solution<br/>(2-5 minutes)"]
    end
    
    subgraph "Real-Time Updates"
        D["Throughout Day:<br/>Schedule Changes"]
        E["/v2/vrp/sync/solve"]
        F["Updated Solution<br/>(< 5 seconds)"]
    end
    
    subgraph "Continuous Operation"
        G["Hundreds of Updates"]
        H["Always Optimal Routes"]
    end
    
    A --> B --> C
    C --> D
    D --> E --> F
    F --> G --> H
    
    style A fill:#e1f5fe
    style B fill:#fff3e0
    style C fill:#e8f5e9
    style D fill:#fce4ec
    style E fill:#fff3e0
    style F fill:#e8f5e9
    style G fill:#f3e5f5
    style H fill:#e8f5e9
```

### Phase 1: Morning Bulk Optimization

Start each day with comprehensive planning using the asynchronous solve endpoint:

<Steps>
  <Step title="Bulk Problem Setup">
    Prepare your complete daily schedule with all known jobs, resources, and constraints.

    ```json theme={null}
    {
      "jobs": [
        {"name": "delivery_001", "location": [4.3517, 50.8503], "duration": 1800},
        {"name": "delivery_002", "location": [2.3522, 48.8566], "duration": 1200},
        // ... 200+ more jobs
      ],
      "resources": [
        {"name": "driver_1", "start": [4.3517, 50.8503]},
        {"name": "driver_2", "start": [4.3517, 50.8503]},
        // ... additional resources
      ]
    }
    ```
  </Step>

  <Step title="Comprehensive Solve">
    Submit to the asynchronous solve endpoint for thorough optimization.

    ```bash theme={null}
    POST /v2/vrp/solve
    ```

    This takes 2-5 minutes but produces the highest quality solution considering all constraints and optimization objectives.
  </Step>

  <Step title="Extract Schedule Foundation">
    Use the complete solution as your baseline schedule for the day.

    ```json theme={null}
    {
      "routes": [
        {
          "resourceId": "driver_1",
          "jobs": [
            {
              "jobId": "delivery_001",
              "arrival": "2024-03-15T09:15:00Z",
              "departure": "2024-03-15T09:45:00Z"
            },
            {
              "jobId": "delivery_002", 
              "arrival": "2024-03-15T11:30:00Z",
              "departure": "2024-03-15T11:50:00Z"
            }
          ]
        }
      ]
    }
    ```
  </Step>
</Steps>

### Phase 2: Real-Time Adjustments

Throughout the day, use the synchronous endpoint for rapid schedule updates:

<Steps>
  <Step title="Current State Capture">
    When changes occur, capture the current schedule state using `initialResource` and `initialArrival` fields.

    ```json theme={null}
    {
      "jobs": [
        {
          "name": "delivery_001",
          "initialResource": "driver_1",
          "initialArrival": "2024-03-15T09:15:00Z",
          "location": [4.3517, 50.8503],
          "duration": 1800
        },
        {
          "name": "new_urgent_job",
          "priority": 100,
          "urgency": 100,
          "location": [3.0686, 50.6365],
          "duration": 900,
          "windows": [{"from": "2024-03-15T10:00:00Z", "to": "2024-03-15T12:00:00Z"}]
        }
      ]
    }
    ```
  </Step>

  <Step title="Rapid Re-optimization">
    Submit to the synchronous solve endpoint for immediate results.

    ```bash theme={null}
    POST /v2/vrp/sync/solve
    ```

    Returns optimized solution in seconds, building on the initial state.
  </Step>

  <Step title="Deploy Updated Schedule">
    Immediately deploy the updated routes to your field teams.

    <Check>
      Synchronous solve completes in under 5 seconds, enabling real-time responsiveness.
    </Check>
  </Step>
</Steps>

## Key Schema Fields for Real-Time Scheduling

The VRP solver provides specific fields designed for real-time operations:

### Initial State Fields

Use these fields to provide the current schedule state to the solver:

<Tabs>
  <Tab title="initialResource">
    ```json theme={null}
    {
      "name": "delivery_001",
      "initialResource": "driver_1",
      "location": [4.3517, 50.8503],
      "duration": 1800
    }
    ```

    **Purpose**: Warm start optimization by indicating which resource is currently assigned to each job.

    **Usage**: Set based on your current schedule to help the solver understand the starting point.
  </Tab>

  <Tab title="initialArrival">
    ```json theme={null}
    {
      "name": "delivery_001", 
      "initialResource": "driver_1",
      "initialArrival": "2024-03-15T09:15:00Z",
      "location": [4.3517, 50.8503],
      "duration": 1800
    }
    ```

    **Purpose**: Indicates the currently planned arrival time for the job.

    **Usage**: Helps the solver understand timing constraints and minimize disruption to existing schedules.
  </Tab>
</Tabs>

### Planned State Fields

Use these fields to create soft constraints around customer commitments:

<Tabs>
  <Tab title="plannedResource">
    ```json theme={null}
    {
      "name": "customer_appointment",
      "plannedResource": "technician_2",
      "plannedArrival": "2024-03-15T14:00:00Z",
      "location": [2.3522, 48.8566],
      "duration": 3600
    }
    ```

    **Purpose**: Creates a hard constraint that this job must be assigned to the specified resource.

    **Usage**: Use for confirmed customer appointments or resource-specific requirements.
  </Tab>

  <Tab title="plannedArrival">
    ```json theme={null}
    {
      "name": "customer_appointment",
      "plannedArrival": "2024-03-15T14:00:00Z",
      "location": [2.3522, 48.8566], 
      "duration": 3600
    }
    ```

    **Purpose**: Creates a soft constraint encouraging the solver to schedule near this time.

    **Usage**: Represents customer appointment times while allowing flexibility for optimization.
  </Tab>
</Tabs>

## Real-Time Scheduling Patterns

### Pattern 1: New Job Insertion

Add urgent jobs to the current schedule:

```json Add Urgent Job theme={null}
{
  "jobs": [
    // Existing jobs with current state
    {
      "name": "existing_001",
      "initialResource": "driver_1", 
      "initialArrival": "2024-03-15T09:15:00Z",
      "location": [4.3517, 50.8503],
      "duration": 1800
    },
    {
      "name": "existing_002",
      "initialResource": "driver_1",
      "initialArrival": "2024-03-15T11:30:00Z", 
      "location": [2.3522, 48.8566],
      "duration": 1200
    },
    // New urgent job
    {
      "name": "urgent_repair",
      "priority": 100,
      "urgency": 100,
      "location": [3.0686, 50.6365],
      "duration": 900,
      "windows": [{"from": "2024-03-15T10:00:00Z", "to": "2024-03-15T12:00:00Z"}]
    }
  ],
  "resources": [
    {"name": "driver_1", "start": [4.3517, 50.8503]}
  ]
}
```

### Pattern 2: Job Cancellation

Remove cancelled jobs and reoptimize remaining schedule:

```json Handle Cancellation theme={null}
{
  "jobs": [
    // Keep only non-cancelled jobs
    {
      "name": "delivery_001",
      "initialResource": "driver_1",
      "initialArrival": "2024-03-15T09:15:00Z",
      "location": [4.3517, 50.8503],
      "duration": 1800
    }
    // delivery_002 removed due to cancellation
  ],
  "resources": [
    {"name": "driver_1", "start": [4.3517, 50.8503]}
  ]
}
```

### Pattern 3: Resource Unavailability

Handle driver breaks, vehicle issues, or other resource constraints:

```json Resource Unavailability theme={null}
{
  "jobs": [
    {
      "name": "delivery_001",
      "initialResource": "driver_2",  // Reassigned from driver_1
      "location": [4.3517, 50.8503],
      "duration": 1800
    },
    {
      "name": "delivery_002",
      "location": [2.3522, 48.8566],
      "duration": 1200
      // No initial assignment - solver will assign to available resource
    }
  ],
  "resources": [
    // driver_1 removed due to unavailability
    {"name": "driver_2", "start": [3.0686, 50.6365]}
  ]
}
```

### Pattern 4: Customer Rescheduling

Handle customer-requested appointment changes:

```json Customer Reschedule theme={null}
{
  "jobs": [
    {
      "name": "customer_appointment",
      "plannedArrival": "2024-03-15T16:00:00Z",  // Moved from 14:00
      "location": [2.3522, 48.8566],
      "duration": 3600,
      "windows": [{"from": "2024-03-15T15:00:00Z", "to": "2024-03-15T17:00:00Z"}]
    },
    // Other jobs with current initial state
    {
      "name": "delivery_001",
      "initialResource": "driver_1",
      "initialArrival": "2024-03-15T09:15:00Z",
      "location": [4.3517, 50.8503],
      "duration": 1800
    }
  ],
  "resources": [
    {"name": "driver_1", "start": [4.3517, 50.8503]}
  ]
}
```

## Implementation Architecture

### Backend Integration

Structure your real-time scheduling system with clear separation between bulk and real-time operations:

<CodeGroup>
  ```javascript Node.js Backend theme={null}
  class RealtimeScheduler {
    async performMorningOptimization(jobs, resources) {
      // Use async solve for comprehensive optimization
      const response = await fetch('/v2/vrp/solve', {
        method: 'POST',
        headers: { 'Authorization': apiKey },
        body: JSON.stringify({ jobs, resources })
      });
      
      const jobId = await response.json();
      
      // Poll for completion
      const solution = await this.pollForSolution(jobId.id);
      
      // Store as baseline schedule
      await this.storeBaselineSchedule(solution);
      
      return solution;
    }
    
    async performRealtimeUpdate(currentState, changes) {
      // Apply current state to jobs
      const jobsWithState = this.applyCurrentState(currentState, changes);
      
      // Use sync solve for rapid response
      const response = await fetch('/v2/vrp/sync/solve', {
        method: 'POST',
        headers: { 'Authorization': apiKey },
        body: JSON.stringify({
          jobs: jobsWithState,
          resources: currentState.resources
        })
      });
      
      const solution = await response.json();
      
      // Deploy immediately to field teams
      await this.deployToField(solution);
      
      return solution;
    }
    
    applyCurrentState(currentState, changes) {
      return currentState.jobs.map(job => ({
        ...job,
        ...changes.jobs?.find(c => c.name === job.name),
        initialResource: job.currentResource,
        initialArrival: job.currentArrival
      }));
    }
  }
  ```

  ```python Python Backend theme={null}
  class RealtimeScheduler:
      def __init__(self, api_key):
          self.api_key = api_key
          self.base_url = 'https://api.solvice.io'
          
      async def perform_morning_optimization(self, jobs, resources):
          """Comprehensive morning optimization using async solve"""
          response = requests.post(
              f'{self.base_url}/v2/vrp/solve',
              headers={'Authorization': self.api_key},
              json={'jobs': jobs, 'resources': resources}
          )
          
          job_id = response.json()['id']
          
          # Poll for completion
          solution = await self.poll_for_solution(job_id)
          
          # Store as baseline
          await self.store_baseline_schedule(solution)
          
          return solution
          
      async def perform_realtime_update(self, current_state, changes):
          """Fast real-time updates using sync solve"""
          jobs_with_state = self.apply_current_state(current_state, changes)
          
          response = requests.post(
              f'{self.base_url}/v2/vrp/sync/solve',
              headers={'Authorization': self.api_key},
              json={
                  'jobs': jobs_with_state,
                  'resources': current_state['resources']
              }
          )
          
          solution = response.json()
          
          # Deploy immediately
          await self.deploy_to_field(solution)
          
          return solution
          
      def apply_current_state(self, current_state, changes):
          """Apply current schedule state to jobs"""
          jobs = []
          for job in current_state['jobs']:
              updated_job = {**job}
              
              # Apply any changes
              if changes.get('jobs'):
                  change = next((c for c in changes['jobs'] if c['name'] == job['name']), None)
                  if change:
                      updated_job.update(change)
              
              # Set initial state
              updated_job['initialResource'] = job.get('currentResource')
              updated_job['initialArrival'] = job.get('currentArrival')
              
              jobs.append(updated_job)
              
          return jobs
  ```
</CodeGroup>

### Performance Optimization

<Tip>
  **Real-Time Performance Tips:**

  1. **Minimize Job Count**: Only include jobs that could be affected by changes
  2. **Use Initial State**: Always provide `initialResource` and `initialArrival` for existing jobs
  3. **Batch Changes**: Group multiple changes into single sync solve calls
  4. **Cache Results**: Store solutions to avoid redundant calculations
  5. **Monitor Timing**: Track sync solve response times to ensure sub-5-second performance
</Tip>

## Error Handling and Resilience

Real-time systems require robust error handling:

### Fallback Strategies

<AccordionGroup>
  <Accordion title="Sync Solve Timeout">
    If sync solve takes too long:

    ```javascript theme={null}
    const SYNC_TIMEOUT = 10000; // 10 seconds

    async function safeRealtimeUpdate(currentState, changes) {
      try {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), SYNC_TIMEOUT);
        
        const solution = await performRealtimeUpdate(currentState, changes, {
          signal: controller.signal
        });
        
        clearTimeout(timeoutId);
        return solution;
        
      } catch (error) {
        if (error.name === 'AbortError') {
          // Fallback to last known good schedule
          return await getFallbackSchedule(currentState);
        }
        throw error;
      }
    }
    ```
  </Accordion>

  <Accordion title="API Unavailability">
    When the API is temporarily unavailable:

    ```javascript theme={null}
    async function performRealtimeUpdateWithFallback(currentState, changes) {
      try {
        return await performRealtimeUpdate(currentState, changes);
      } catch (error) {
        if (error.status >= 500) {
          // Server error - use local optimization
          return await localFallbackOptimization(currentState, changes);
        }
        throw error;
      }
    }
    ```
  </Accordion>

  <Accordion title="Invalid Solution">
    When optimization returns an infeasible solution:

    ```javascript theme={null}
    function validateSolution(solution, currentState) {
      // Check for unassigned critical jobs
      const criticalUnassigned = solution.unassigned?.filter(job => 
        job.priority > 90 || job.urgency > 90
      );
      
      if (criticalUnassigned?.length > 0) {
        throw new Error(`Critical jobs unassigned: ${criticalUnassigned.map(j => j.name)}`);
      }
      
      return true;
    }
    ```
  </Accordion>
</AccordionGroup>

## Operational Considerations

### Update Frequency

<Warning>
  **Update Frequency Guidelines:**

  * Maximum: 1 update per 30 seconds per resource
  * Recommended: Batch changes and update every 2-5 minutes
  * Emergency: Immediate updates for critical changes only
</Warning>

### State Management

Track the current schedule state to enable effective real-time updates:

```json theme={null}
{
  "scheduleVersion": "2024-03-15-v47",
  "lastUpdated": "2024-03-15T10:45:00Z",
  "jobs": [
    {
      "name": "delivery_001",
      "currentResource": "driver_1",
      "currentArrival": "2024-03-15T09:15:00Z",
      "status": "completed"
    },
    {
      "name": "delivery_002", 
      "currentResource": "driver_1",
      "currentArrival": "2024-03-15T11:30:00Z",
      "status": "in_progress"
    },
    {
      "name": "delivery_003",
      "currentResource": "driver_1", 
      "currentArrival": "2024-03-15T13:45:00Z",
      "status": "scheduled"
    }
  ]
}
```

### Monitoring and Analytics

Track key metrics for real-time scheduling performance:

<CardGroup cols={2}>
  <Card title="Optimization Speed" icon="stopwatch">
    Monitor sync solve response times and ensure they stay under 5 seconds
  </Card>

  <Card title="Schedule Stability" icon="chart-line">
    Track how often schedules change and the magnitude of disruptions
  </Card>

  <Card title="Customer Impact" icon="users">
    Measure appointment changes and customer notification requirements
  </Card>

  <Card title="Resource Utilization" icon="truck">
    Monitor how real-time changes affect overall resource efficiency
  </Card>
</CardGroup>

## Best Practices

<Check>
  **Real-Time Scheduling Best Practices:**

  1. **Morning Foundation**: Always start with comprehensive bulk optimization
  2. **State Preservation**: Maintain accurate current state with `initialResource` and `initialArrival`
  3. **Change Batching**: Group multiple changes to minimize optimization calls
  4. **Error Resilience**: Implement fallback strategies for API failures
  5. **Performance Monitoring**: Track optimization times and schedule stability
  6. **Customer Communication**: Automate notifications when appointments change
  7. **Resource Coordination**: Ensure field teams receive updates immediately
  8. **Data Integrity**: Validate solutions before deployment
</Check>

## Common Use Cases

### Emergency Response

Handle urgent service requests that must be inserted into existing schedules with minimal disruption.

### Dynamic Demand

Adapt to changing customer demands throughout the day, such as same-day delivery requests or appointment changes.

### Resource Management

Respond to driver breaks, vehicle breakdowns, traffic delays, and other resource availability changes.

### Service Quality

Maintain optimal routes while respecting customer commitments and service windows.

## Related Topics

<CardGroup cols={2}>
  <Card title="Sync Solve API" icon="zap" href="/api-reference/vrp/sync-solve">
    Fast synchronous optimization endpoint
  </Card>

  <Card title="Async Solve API" icon="clock" href="/api-reference/vrp/solve">
    Comprehensive asynchronous optimization
  </Card>

  <Card title="Job Schemas" icon="list" href="/guides/vrp/schemas/request">
    Complete job configuration options
  </Card>

  <Card title="Performance Guide" icon="gauge" href="/guides/vrp/concepts/performance-guide">
    Optimize solving performance
  </Card>
</CardGroup>
