We need to design a resilient scheduler for long jobs that supports leases, checkpoints, and preemption. This is likely for a distributed system or HPC cluster. We need to think about how to handle long-running jobs that may be preempted, checkpoints for recovery, and leases for resource allocation with time limits. The scheduler should be resilient to failures, meaning it can recover from node failures, network partitions, etc. Also, it should handle preemption (i.e., higher priority jobs can evict lower priority ones) and leases (temporary resource reservations that expire). Checkpoints allow jobs to save state so that they can be restarted from a recent point rather than from scratch.
We need to design the system: components, data structures, algorithms, and protocols. Let's outline:
-
System Model:
- A set of compute nodes (workers) that can execute tasks.
- A central scheduler (or distributed?) For resilience, maybe we want a replicated state machine or fault-tolerant scheduler. But for simplicity, we can have a primary-backup scheduler, or a distributed consensus-based scheduler. But the problem likely expects a design focusing on how to handle leases, checkpoints, and preemption, not necessarily the scheduler's own fault tolerance. However, "resilient scheduler" might imply the scheduler itself is resilient to failures. But maybe it's about scheduling jobs resiliently (i.e., jobs can survive preemption and failures). We'll assume the scheduler is a component that manages resources and job execution, and we need to design it to be robust.
Alternatively, we could design a scheduler that is part of a larger system like a cluster manager (e.g., YARN, Mesos, Kubernetes). But we need to incorporate leases (like in Omega? or in some scheduling algorithms for cloud), checkpoints, and preemption.
Let's define:
-
Jobs: long-running, possibly composed of multiple tasks. They can be preemptible (i.e., can be killed and restarted) or non-preemptible? But since we want preemption, we assume jobs can be preempted. But some jobs might be non-preemptible; we can handle them with higher priority or by using lease extensions.
-
Leases: When a job acquires resources, it gets a lease for a certain time. If it doesn't checkpoint within the lease period, it might be killed. Or lease is a way to bound resource usage and allow preemption. Maybe lease is like a time-bound reservation: a job can hold resources for a lease duration, after which it must renew or release. This allows the scheduler to reclaim resources.
-
Checkpoints: Jobs periodically save their state to stable storage. On preemption or failure, they can be restarted from the last checkpoint. Checkpointing has overhead, so jobs might checkpoint at intervals.
-
Preemption: Higher priority jobs can cause lower priority jobs to be preempted. When preempted, the job's resources are taken away, but the job can later be resumed from a checkpoint.
So the scheduler needs to track:
- Job states: running, waiting, preempted, checkpointing, etc.
- Resource reservations: leases with expiration times.
- Checkpoint history for each job: where checkpoints are stored, timestamps.
- Priority of jobs.
The scheduler must decide when to preempt, when to evict, and how to allocate resources considering lease durations and checkpoint frequencies.
-
Design Goals:
- High utilization: but not starve long jobs.
- Fairness? Possibly weighted fairness.
- Resilience: jobs can survive preemptions and failures.
- Bounded preemption overhead: checkpointing cost and restart cost should be minimized.
- Predictable performance: leases allow jobs to know how long they can run without interruption.
-
High-level Approach:
-
Use a lease-based resource allocation: when a job is scheduled, it gets resources for a lease period (e.g., 1 hour). It can request lease extensions. The lease duration may be based on job's expected runtime or checkpoint interval. The scheduler can revoke leases early for preemption.
-
Checkpointing: The job itself is responsible for checkpointing at appropriate times (driven by time or progress). The scheduler may advise or enforce checkpoint intervals? Possibly the scheduler can require that a job checkpoint before its lease expires, or else it will be killed. But preemption can happen at any time, so jobs should checkpoint frequently enough to limit lost work.
-
Preemption: When a high-priority job arrives, the scheduler selects lower-priority jobs to preempt. It may choose jobs that have no lease? Or those that are on lease? Actually, all jobs have leases. The scheduler can revoke leases (i.e., preempt) by sending a preemption signal. The preempted job should have a recent checkpoint to restart quickly. So the scheduler might prioritize preempting jobs that have a recent checkpoint (i.e., low "progress since last checkpoint") to minimize waste. Also, it might avoid preempting jobs that are about to finish their lease and will be released anyway.
-
Resilience to node failures: If a node fails, the scheduler must detect and reschedule jobs from their last checkpoint. This is independent of preemption but also uses checkpoints.
-
Checkpoint storage: Checkpoints are stored in a distributed storage system (e.g., HDFS, S3). The scheduler needs to know where checkpoints are stored and their validity.
-
Architecture:
Components:
a. Scheduler Core: makes decisions about resource allocation, lease management, preemption. It maintains a global view of resource usage, jobs, leases, priorities.
b. Lease Manager: Tracks active leases, their expiration, and handles lease renewal requests from jobs.
c. Checkpoint Manager: Keeps track of checkpoints for each job, storage locations, timestamps. It may also store metadata about checkpoint completeness (e.g., all tasks checkpointed). Possibly the job reports checkpoint completion to the scheduler.
d. Node Agent: Runs on each worker node, responsible for launching tasks, monitoring them, enforcing preemption (e.g., sending SIGTERM, then SIGKILL), and handling checkpoint requests from tasks. It also reports heartbeats to the scheduler.
e. Job Manager (client-side): The job's driver program (or a per-job agent) that interacts with the scheduler: requests resources, reports progress, requests lease renewals, triggers checkpoints, and handles preemption notifications.
Alternatively, we could have a more centralized design: the scheduler directly communicates with tasks to preempt and checkpoint. But typical designs have an agent on nodes.
-
Data Structures:
-
JobInfo: jobId, priority, totalResourceRequest (e.g., number of cores, memory), currentAllocation (set of resource offers), state (WAITING, RUNNING, PREEMPTED, COMPLETED, FAILED), checkpointMetadata (list of checkpoints with timestamps and storage URIs), leaseExpiryTime, lastCheckpointTime, etc.
-
Lease: jobId, resourceOffer (resources allocated), expireTime, renewalCount? Or leaseId.
-
ResourceOffer: nodeId, resources (CPU, memory, disk, etc.). When a lease is granted, the resources are reserved.
-
NodeInfo: nodeId, total resources, allocated resources, state (UP, DOWN, DRAINING), lastHeartbeat.
-
Checkpoint: checkpointId, jobId, timestamp, storageUri, isComplete (maybe all tasks have written), size.
The scheduler keeps a priority queue of jobs for scheduling? Actually, it uses a scheduling policy: e.g., greedy packing, bin packing, etc. But for preemption, we need to select victims.
-
Algorithms:
a. Scheduling new jobs:
When a job arrives, the scheduler tries to find resources to satisfy its request. It may preempt existing jobs if needed. It grants a lease with an initial duration (maybe based on job's requested runtime or a default). It sends resource offers to the job's manager, which then launches tasks on the nodes.
b. Lease renewal:
Before lease expires, the job can request renewal. The scheduler may grant extension if resources are available and job priority is high enough. If not, the job may be preempted at expiry.
c. Preemption:
When a high-priority job arrives or resources are needed, the scheduler selects one or more lower-priority jobs to preempt. Selection criteria:
- Minimize waste: choose jobs that have a recent checkpoint (i.e., small amount of work since last checkpoint) because preempting them loses less progress.
- Consider lease expiry: jobs that are about to expire anyway may be good candidates.
- Avoid preempting jobs that have never checkpointed? Maybe penalize.
Once selected, the scheduler sends preemption signals to those jobs' managers or directly to nodes. The preempted job should be given a grace period to checkpoint (if it hasn't recently). After checkpoint, resources are reclaimed.
d. Checkpointing:
The job decides when to checkpoint. It coordinates with its tasks to create a consistent snapshot. The checkpoint data is written to stable storage. After completion, the job notifies the scheduler with checkpoint metadata. The scheduler updates the job's lastCheckpointTime.
The scheduler may also enforce a maximum time between checkpoints (e.g., to bound lost work on preemption). It could send a warning if a job hasn't checkpointed within a certain time.
e. Failure handling:
If a node fails (detected via missed heartbeats), the scheduler marks all leases on that node as revoked. It then reschedules the affected jobs from their latest checkpoint (if any). The jobs are moved back to WAITING state, and the scheduler tries to allocate resources again.
f. Resilience of scheduler itself: To make the scheduler resilient, we could run multiple replicas with consensus (e.g., using Raft). The state (jobs, leases, checkpoints) must be replicated. When the primary fails, a new one is elected with the latest state. This is complex but doable. Alternatively, we can design the scheduler to be stateless and rely on a distributed store? But scheduler state is complex. Maybe we assume the scheduler is fault-tolerant via replication. We can mention that.
-
Lease Details:
- A lease is a contract: the job can use the resources for the lease duration. The scheduler can revoke it earlier (preemption) but not extend without renewal.
- Leases help to bound the time a job can hold resources without checkpointing? Not directly, but we can tie lease renewal to checkpointing: a job must have checkpointed within the last X time to be eligible for renewal. This encourages frequent checkpointing.
Alternatively, leases could be used for advance reservations (future start times) but that might be less relevant.
-
Checkpoint Overhead:
- The system should minimize checkpoint overhead. The scheduler can advise an optimal checkpoint interval based on job's progress rate and preemption probability. But that's advanced.
-
Preemption Grace Period:
- When preempting, the scheduler sends a preemption notice. The job is given a grace period (e.g., a few minutes) to checkpoint and exit gracefully. If it doesn't, the scheduler force kills tasks.
-
Resource Reclamation:
- After preemption or lease expiry, resources are freed and can be allocated to new jobs.
-
Implementation Considerations:
- Use a message queue or RPC for communication.
- The scheduler should be able to handle thousands of jobs and nodes.
- Scalability: Partition the cluster into zones with local schedulers and a global coordinator? But for simplicity, assume a centralized scheduler with replicated state.
-
Extended Features:
- Support for different preemption policies: e.g., priority-based, fairness-based, or deadline-based.
- Support for gang scheduling? Possibly not needed.
- Support for elasticity: jobs can request more resources dynamically? Could be but keep simple.
Now, we need to produce a design document. Let's structure:
- Introduction: Overview and goals.
- System Model: Assumptions about nodes, jobs, failures.
- Architecture: Components and their responsibilities.
- Data Model: Key data structures and how they are stored.
- Core Algorithms:
- Job Submission and Initial Allocation
- Lease Management
- Checkpointing Protocol
- Preemption Protocol
- Failure Recovery
- Resilience of Scheduler: Replication and fault tolerance.
- Optimizations: e.g., victim selection, lease renewal hints, checkpoint frequency adaptation.
- Discussion: Trade-offs, limitations, comparisons.
We need to be detailed but not overly verbose.
Let's flesh out each part.
Introduction:
We design a resilient scheduler for long-running jobs in a cluster. The scheduler ensures that jobs can survive preemptions and node failures via checkpointing, while also supporting leases for time-bound resource allocation and allowing higher-priority jobs to preempt lower-priority ones. The design aims for high resource utilization and bounded disruption.
System Model:
- Compute nodes: each with a fixed set of resources (CPU cores, memory, disk, network). Nodes can fail and recover. Nodes run an agent (Node Agent) that manages tasks.
- Jobs: Each job has a unique ID, a priority (static or dynamic), a resource request (vector), and a logical program that can be split into tasks. Jobs are preemptible: they can be suspended and later resumed from a checkpoint. Jobs are responsible for generating checkpoints at appropriate times. Checkpoints are stored in a reliable distributed storage system.
- Scheduler: A logically centralized component (replicated for fault tolerance) that arbitrates resource allocation, manages leases, and coordinates preemption and recovery.
- Communication: Scheduler communicates with Job Managers (clients) and Node Agents via RPC. Node Agents send periodic heartbeats.
Architecture:
- Scheduler Core: Main decision-making entity. It runs as a replicated state machine (e.g., using Raft) for fault tolerance. It maintains global state (jobs, leases, nodes) and processes events (job submission, heartbeats, lease expiry, preemption requests).
- Lease Manager: Subcomponent that tracks active leases. Each lease is associated with a job and a set of resources on specific nodes. It handles lease expiration events and renewal requests.
- Checkpoint Registry: Stores metadata about checkpoints: jobId, checkpointId, timestamp, storage location, completeness flag. It also tracks the latest checkpoint for each job. It may be integrated with the scheduler's state.
- Node Monitor: Listens to heartbeats from Node Agents. Detects node failures (missed heartbeats) and triggers recovery.
- Preemption Controller: When resources are needed for higher-priority jobs, it selects victim jobs based on policies and initiates preemption.
- Scheduling Engine: Packing algorithm to allocate resources to jobs, considering existing allocations and pending requests.
The scheduler exposes APIs:
submitJob(jobSpec): returns jobId.
requestLeaseRenewal(jobId, leaseId): job requests to extend lease.
reportCheckpoint(jobId, checkpointMeta): job reports a new checkpoint.
heartbeat(nodeId, resources): from node agent.
preemptJob(jobId): internal, used by preemption controller to mark job for preemption.
Additionally, Job Manager (client-side) and Node Agent have their own responsibilities.
Data Model:
We'll define in more detail.
Core Algorithms:
1. Job Submission and Initial Allocation:
- When a job is submitted, the Scheduler Core creates a Job entry with state WAITING.
- The Scheduling Engine attempts to find a feasible set of resources to satisfy the job's request. It looks at nodes with available resources. If enough resources are free, it allocates them by creating ResourceOffers and a Lease with a default duration (e.g., 1 hour). The lease expireTime = now + leaseDuration.
- If not enough free resources, the scheduler considers preempting lower-priority jobs. It invokes the Preemption Controller to select victims. The preemption is "preemptive scheduling": we may need to free a certain amount of resources. The Preemption Controller selects one or more victim jobs such that their total allocated resources meet or exceed the deficit. Selection criteria (see below). It then marks those jobs for preemption and triggers the preemption process. After resources are reclaimed, the new job is allocated.
- Once allocation is decided, the scheduler sends resource offers to the Job Manager, which then dispatches tasks to the respective Node Agents. The job state becomes RUNNING.
2. Lease Management:
- Each lease has an expireTime. The Lease Manager runs a periodic task (or uses a timing wheel) to check for leases that will expire soon (e.g., within 5 minutes). It can send renewal reminders to the Job Manager. The Job Manager may request renewal if it wants to continue.
- Renewal request: Job Manager calls
requestLeaseRenewal(jobId, leaseId). The Lease Manager checks if the job is still RUNNING, and if resources are still available (or can be kept). It may grant extension (e.g., add 1 hour) and update expireTime. If not, it denies, and the lease will expire, leading to preemption.
- Lease Expiry: When a lease expires (or is revoked due to preemption), the Lease Manager marks it as EXPIRED/REVOKED and triggers resource reclamation. The Job Manager is notified. The job should have already checkpointed (or be given a grace period). After reclamation, resources become available.
3. Preemption Protocol:
- Preemption can be triggered by:
a. Arrival of a high-priority job that needs resources.
b. Lease renewal denial.
c. System maintenance.
- The Preemption Controller selects victims. Selection algorithm:
-
Consider all RUNNING jobs with priority lower than the preempting job's priority (or if not priority-based, maybe based on fairness deficit).
-
For each job, compute a "preemption cost" = resources allocated * (1 - checkpoint freshness). Actually, we want to minimize lost work. If a job last checkpointed at time t_ckpt, and current time t_now, then work lost if preempted now = progress rate * (t_now - t_ckpt). But we don't know progress rate exactly. We can approximate by the time since last checkpoint: longer since last checkpoint means more lost work. So we want to preempt jobs that have a recent checkpoint (small time since last checkpoint). Also, we might want to avoid preempting jobs that have a lease expiring soon (because they'll free resources anyway). So we can compute a score: score = (timeSinceLastCheckpoint) / leaseTimeRemaining? Or simpler: sort ascending by timeSinceLastCheckpoint (smallest first) and descending by priority? Actually, we want to pick victims that minimize waste, so we pick jobs with smallest timeSinceLastCheckpoint. But we also need to free enough resources. So we can select victims in order of increasing timeSinceLastCheckpoint until we free enough resources. However, if we preempt a job that just checkpointed, it loses little. But if we preempt a job that hasn't checkpointed for a long time, it loses a lot. So we want to avoid that. So indeed select those with recent checkpoints.
-
Additionally, consider job's remaining work? Not known.
-
After selecting victims, the Preemption Controller instructs the Lease Manager to revoke their leases. It sends a preemption signal to each victim's Job Manager (or directly to Node Agents). The signal includes a deadline (e.g., 5 minutes) by which they must checkpoint and exit.
-
The victim job's Job Manager coordinates a checkpoint: it instructs its tasks to flush state to checkpoint storage. Once all tasks have checkpointed, it reports the new checkpoint to the Checkpoint Registry. Then it releases resources (tasks exit). The Node Agents monitor tasks and kill them after deadline if not exited.
-
If a job fails to checkpoint in time, the scheduler force kills tasks and reclaims resources. The job may lose more progress but can still recover from the previous checkpoint.
-
After resources are reclaimed, the preempting job can be allocated.
4. Checkpointing Protocol:
-
Checkpointing can be initiated by the job (periodically) or by the scheduler (e.g., as a preemption warning). Job Manager decides when to checkpoint, possibly based on time elapsed or progress milestones. It sends a checkpoint command to all its tasks.
-
Each task checkpoints its local state to the distributed storage (maybe directly to HDFS). The task must ensure the checkpoint is durable (fsync?).
-
After a task completes checkpoint, it notifies the Job Manager. The Job Manager tracks which tasks have checkpointed.
-
Once all tasks have checkpointed, the Job Manager creates a global checkpoint metadata (consistent snapshot) and reports it to the scheduler's Checkpoint Registry via reportCheckpoint. This includes the storage URIs for each task's checkpoint (or a manifest).
-
The scheduler updates the job's lastCheckpointTime and the list of checkpoints. It may also prune old checkpoints to save space (maybe keep last N).
-
For efficiency, checkpoints can be incremental (only changes since last checkpoint). The design doesn't need to specify details.
-
During preemption, the scheduler may send a "preempt and checkpoint" command with a deadline. The Job Manager then initiates an urgent checkpoint.
5. Failure Recovery:
-
Node Agent sends heartbeats every few seconds. If the Node Monitor doesn't receive heartbeat for a timeout (e.g., 30 seconds), it marks the node as UNHEALTHY.
-
All leases on that node are considered revoked. The Lease Manager marks those leases as REVOKED due to failure.
-
For each job that had tasks on the failed node, the scheduler marks the job as PREEMPTED? Actually, the job is still RUNNING but missing resources. It might be partially failed. The scheduler should treat it as a partial failure: the job continues on remaining nodes if it can? But for simplicity, we can assume the job is entirely on that node? In many systems, a job may have multiple tasks across nodes. If one node fails, the tasks on that node are lost. The job may need to reschedule those tasks from a checkpoint. So we need to handle node failure as a special case of preemption but without grace period? Actually, we can treat it similarly: the job loses resources suddenly. The scheduler should reschedule the job's tasks on other nodes, but the job itself may still be running on other nodes. That's tricky. To keep simple, we could assume that a job's tasks are all on one node? That's unrealistic. Alternatively, we can treat the job as still RUNNING, but we need to re-launch the failed tasks. However, if the node fails, the tasks are gone, and the job might be stuck unless it checkpoints and restarts those tasks. But the job might be designed to handle task failures (e.g., map-reduce). But our scheduler is for long jobs, which may be monolithic (like a single process) or parallel. Let's assume the job is a collection of tasks that are scheduled independently; a node failure causes tasks on that node to be lost. The scheduler can reschedule those tasks on other nodes, but the job's state must be consistent. That's why checkpointing is needed: the job can be restarted from a checkpoint after a node failure. However, if only some tasks fail, the job might not need a full restart; it could recompute lost tasks from the last checkpoint. That's more complex. To simplify, we could treat the entire job as a unit: when any node fails, the whole job is preempted and rescheduled from the last checkpoint. That is easier: the job is allocated resources on a set of nodes; if any node fails, the lease on all those nodes is revoked and the job is rescheduled from checkpoint. This is coarse-grained but simpler. Alternatively, we could have fine-grained: tasks are independent and can be restarted individually, but then we need a task-level checkpoint. Let's go with coarse-grained job-level allocation: each job gets a set of resources (nodes) and runs on them. If any node fails, the job loses all its resources and is considered preempted. Then scheduler reschedules it from the latest checkpoint. That aligns with preemption: both cause loss of resources. So we can treat node failure as an involuntary preemption.
-
So upon node failure, the scheduler marks all jobs on that node as PREEMPTED (or RUNNING? Actually, they lost resources, so they become WAITING? But they have a checkpoint, so they can be rescheduled). The scheduler will then attempt to reallocate those jobs, possibly after a delay to allow checkpoint? But they might have already checkpointed recently. The scheduler can immediately try to schedule them again, but maybe with lower priority? We can treat it similarly to preemption: the job enters a "RECOVERING" state and then goes back to WAITING to be rescheduled. The Checkpoint Registry provides the latest checkpoint to restart from. The Job Manager, upon notification of node failure, can also initiate a checkpoint if possible before the node completely dies? But if node failed, it's too late. So we rely on the last checkpoint.
Resilience of Scheduler:
- The scheduler itself is a critical component. To make it resilient, we run multiple instances (e.g., 3) with leader election using Raft. All state changes go through the Raft log and are replicated. The state includes job table, lease table, node table, checkpoint registry. If the leader fails, a new leader is elected with the latest state. This ensures no single point of failure.
- For performance, the leader handles all requests; followers replicate. Clients (Job Managers, Node Agents) only talk to the leader. They may need to discover the leader via a service registry or by contacting any scheduler and getting redirected.
Optimizations:
-
Victim Selection: Use a scoring function that combines time since last checkpoint and lease remaining time. For job j: score = (t_now - lastCheckpointTime) / (leaseExpireTime - t_now) maybe? Actually, we want to preempt jobs that have high waste ratio. But simpler is fine.
-
Lease Duration: The default lease duration could be adaptive: longer for jobs that checkpoint infrequently? But we want to encourage frequent checkpointing to reduce preemption loss. We could set lease duration to be slightly larger than the maximum allowed time between checkpoints. For example, if we enforce that a job must checkpoint at least every T minutes, then lease duration could be T + epsilon. That way, if a job fails to checkpoint before lease expiry, it will be killed anyway. But we could also allow lease renewal only if checkpointed recently.
-
Preemption Grace Period: The scheduler can send a preemption warning in advance (e.g., 10 minutes before lease expiry) to give time for checkpoint. But for urgent preemption due to high-priority job, we might give a shorter grace period.
-
Checkpoint Throttling: To avoid overloading storage during mass preemption (e.g., if many jobs are preempted at once), the scheduler could stagger preemptions or limit checkpoint I/O. But that's an implementation detail.
-
Elasticity: Jobs could request additional resources mid-run. The scheduler could grant via lease expansion.
Discussion:
- Trade-offs: Frequent checkpointing reduces lost work but increases overhead (I/O, CPU). The system balances by allowing jobs to decide but with incentives (shorter leases or preemption policies favor recent checkpoints).
- The design assumes jobs are cooperative: they must implement checkpointing and respond to preemption signals. If a job misbehaves (ignores preemption), the scheduler can force kill after grace period.
- The centralized scheduler may become a bottleneck; can be partitioned by cluster domains.
- Comparison to existing systems: Similar to Hadoop YARN with preemption and checkpointing? YARN has preemption but not integrated checkpoints. Our design explicitly uses checkpoints for resilience.
Now we need to produce a final answer: a design description. We'll write in a structured manner.
Let's produce the final answer.
Design of a Resilient Scheduler for Long Jobs with Leases, Checkpoints, and Preemption
1. Introduction
We present a scheduler design for clusters executing long-running jobs (e.g., scientific simulations, data processing pipelines). The scheduler must:
- Tolerate preemption (higher‑priority jobs can evict lower‑priority ones).
- Recover from failures (node crashes, network partitions) via checkpoints.
- Bound resource usage using leases (time‑limited reservations).
- Remain resilient itself (survive scheduler node failures).
The design targets high resource utilization, minimal wasted work on preemption/failure, and predictable job execution.
2. System Model
- Nodes: Worker machines with measurable resources (CPU cores, memory, disk, network). Nodes can fail and recover. Each runs a Node Agent that launches/monitors tasks and sends heartbeats.
- Jobs: Each job has a unique ID, a priority (static integer), a total resource request (vector), and is preemptible: it can be suspended and later resumed from a checkpoint. Jobs are composed of tasks that can be placed on any node. A job’s driver is the Job Manager (client‑side component).
- Storage: A reliable distributed storage system (e.g., HDFS, cloud object store) holds checkpoint data durably.
- Scheduler: A logically centralized component that arbitrates resource allocation. It is replicated for fault tolerance (Raft consensus). All state changes go through the leader.
- Communication: Synchronous RPC (or gRPC) between scheduler, job managers, and node agents. Node agents send periodic heartbeats.
3. Architecture Overview
The scheduler consists of the following subcomponents:
- Core: Implements the state machine, processes events, and invokes other subcomponents.
- Lease Manager: Tracks active leases, their expiration times, and handles renewal requests.
- Checkpoint Registry: Persists checkpoint metadata (job ID, timestamp, storage URI, completeness). Integrated into the scheduler’s replicated state.
- Node Monitor: Observes heartbeats; detects node failures.
- Preemption Controller: Selects victim jobs when resources are needed for higher‑priority work.
- Scheduling Engine: Packs jobs onto nodes, respecting resource constraints and preemption decisions.
External actors:
- Job Manager: Submits jobs, requests lease renewals, reports checkpoints, and reacts to preemption signals.
- Node Agent: Accepts task launch/stop commands, monitors tasks, executes checkpoint requests locally, and reports heartbeats.
4. Data Model
All data stored in the scheduler’s replicated state (e.g., in a log‑structured store).
Job
{
"jobId": "string",
"priority": "int",
"request": {"cpu": N, "mem": M, ...},
"state": "WAITING|RUNNING|PREEMPTED|COMPLETED|FAILED",
"allocation": [
{"nodeId": "node1", "resources": {"cpu": n1, "mem": m1}},
...
],
"lease": {"leaseId": "l1", "expireTime": "timestamp", "status": "ACTIVE"},
"checkpoints": [
{"ckptId": "c1", "timestamp": "t", "storageUri": "uri", "complete": true},
...
],
"lastCheckpointTime": "timestamp"
}
Lease
{
"leaseId": "string",
"jobId": "string",
"resources": [{"nodeId": "...", "cpu": ..., ...}],
"issueTime": "timestamp",
"expireTime": "timestamp",
"status": "ACTIVE|EXPIRED|REVOKED",
"renewalCount": "int"
}
Node
{
"nodeId": "string",
"totalResources": {...},
"allocatedResources": {"jobId": {...}},
"state": "HEALTHY|UNHEALTHY|DRAINING",
"lastHeartbeat": "timestamp"
}
5. Core Algorithms
5.1 Job Submission & Initial Allocation
- Job Manager calls
submitJob(spec) → Scheduler creates Job entry (state=WAITING).
- Scheduling Engine searches for free resources to satisfy the request.
- If sufficient free resources exist: allocate them, create a
Lease with default duration L (e.g., 1 hour), set expireTime = now + L, update job state to RUNNING, send resource offers to Job Manager.
- If insufficient free resources: invoke Preemption Controller to free enough resources from lower‑priority jobs (see §5.4). After reclamation, repeat allocation.
- Job Manager launches tasks on the offered nodes via Node Agents.
5.2 Lease Management
- Renewal: Before a lease expires (e.g., 5 min prior), the Lease Manager may send a renewal warning to the Job Manager. The Job Manager can request renewal via
requestLeaseRenewal(jobId, leaseId).
- The Lease Manager checks if the job is still RUNNING and resources remain available (or can be kept). If yes, it extends
expireTime (e.g., by L) and increments renewalCount; otherwise, it denies.
- Expiry/Revocation: When a lease reaches
expireTime (or is revoked by preemption), the Lease Manager marks it EXPIRED/REVOKED, triggers resource reclamation, and notifies the Job Manager. The job must have checkpointed recently; otherwise, it loses work.
5.3 Checkpointing Protocol
- Checkpointing is initiated by the Job Manager, either periodically (based on time or progress) or upon receiving a preemption warning.
- Steps:
- Job Manager broadcasts
checkpoint to all tasks.
- Each task writes its state to distributed storage (e.g., local disk → flush → copy to HDFS). The storage URI is returned.
- Tasks report
checkpointComplete(ckptMeta) to Job Manager.
- Once all tasks have reported, the Job Manager assembles a global checkpoint metadata (manifest) and calls
reportCheckpoint(jobId, ckptMeta) to the Scheduler’s Checkpoint Registry.
- Scheduler updates
lastCheckpointTime and appends to the job’s checkpoint list.
- Preemption‑driven checkpoint: The scheduler sends
preempt(deadline) to the Job Manager, which then initiates an urgent checkpoint before the deadline.
- Failure‑driven checkpoint: Not applicable; checkpointing is proactive.
5.4 Preemption Protocol
Preemption occurs when:
- A higher‑priority job arrives and needs resources.
- A lease renewal is denied.
- System maintenance.
Victim Selection (by Preemption Controller):
- Consider all RUNNING jobs with lower priority than the preempting job (or those that exceed fairness targets).
- For each candidate job j, compute a preemption cost approximated by time since last checkpoint (
t_now - lastCheckpointTime). A smaller value means less work will be lost.
- Sort candidates ascending by time‑since‑last‑checkpoint. Pick victims in that order until the total allocated resources meet the deficit.
- Optionally, factor in lease remaining time: avoid preempting jobs that will release resources soon anyway (i.e.,
expireTime - t_now is small). A combined score could be (timeSinceCkpt) / (leaseTimeRemaining + ε).
Preemption Execution:
- Preemption Controller instructs Lease Manager to revoke the selected victims’ leases (set status REVOKED, set
expireTime = now).
- Scheduler sends
preempt(deadline = now + gracePeriod) to each victim’s Job Manager (gracePeriod e.g., 5 min).
- Victim Job Manager initiates a checkpoint (unless one already exists within a short window). After checkpoint completion and reporting, it tells its tasks to exit.
- Node Agents monitor tasks; if they do not exit by the deadline, the agents force‑kill them.
- Once all tasks of a victim have terminated, the Lease Manager reclaims the resources; the victim job state becomes WAITING (or COMPLETED if it finished before deadline). The resources become available for the preempting job.
5.5 Failure Recovery
- Node failure detection: Node Agent heartbeats every H seconds. If no heartbeat for
timeout (e.g., 3*H), Node Monitor marks the node UNHEALTHY.
- Lease revocation on failure: All leases on the failed node are immediately marked REVOKED by the Lease Manager.
- Job recovery: For each job that had resources on the failed node, the scheduler treats it as involuntarily preempted:
- The job state is set to WAITING (or a RECOVERING state).
- The job’s latest checkpoint (via Checkpoint Registry) is used when it is rescheduled.
- The Scheduling Engine will eventually reallocate the job (subject to its priority) on healthy nodes, providing the resources and a new lease.
- If a job repeatedly fails on the same or similar nodes, the scheduler may delay further attempts or mark the job as FAILED after configurable thresholds.
6. Scheduler Resilience
The scheduler itself is replicated using Raft (or similar consensus):
- Multiple scheduler instances (e.g., 3) maintain identical state via log replication.
- One instance is the leader; all client requests (job submission, heartbeats, etc.) are routed to the leader (clients discover leader via a service registry or by trying any instance and being redirected).
- The Raft log contains all state‑changing operations (job create, lease grant, checkpoint record, etc.). Upon leader crash, a new leader is elected with the latest committed log. This guarantees that all decisions (allocations, preemptions, checkpoints) are not lost.
- For performance, read‑only operations (e.g., job status query) may be served by followers if they can guarantee linearizability (via lease or read‑index).
7. Optimizations & Policies
7.1 Lease Duration & Checkpoint Frequency
- The default lease duration L is chosen to be slightly larger than the maximum allowed interval between checkpoints (enforced by policy). For example, if a job must checkpoint at least every 30 min, set L = 35 min. This ensures the scheduler can revoke leases of jobs that stop checkpointing.
- Job Managers may request a custom lease duration based on expected runtime; the scheduler may grant or adjust based on cluster load.
7.2 Adaptive Preemption Cost
- Besides time‑since‑last‑checkpoint, the cost could incorporate checkpoint size (large checkpoints imply high I/O overhead if we force a new one) and remaining work (if progress rate is known). Simpler deployments stick to time‑since‑checkpoint.
7.3 Grace Period Tuning
- For preemption due to lease expiry (expected), the scheduler sends an early warning (e.g., 10 min before expiry) and allows a long grace period for checkpoint.
- For urgent preemption (high‑priority job arrival), the grace period may be shorter (e.g., 2 min), accepting more work loss for latency.
7.4 Checkpoint Throttling
- During massive preemption (many victims simultaneously), the scheduler could stagger preemption signals or limit concurrent checkpoint I/O to avoid storage overload.
7.5 Elasticity (Optional)
- Jobs may request additional resources mid‑execution. The scheduler can treat it as a new allocation request, possibly preempting other jobs or waiting for free resources, and then expanding the job’s lease.
8. Discussion
Trade‑offs
- Checkpoint Overhead vs. Lost Work: Frequent checkpoints reduce lost work on preemption/failure but increase I/O and CPU load. The design lets jobs choose their frequency but incentivizes frequent checkpoints via preemption victim selection and lease policies.
- Coarse‑grained Allocation: We assume a job’s tasks are scheduled as a unit on a fixed set of nodes. If a node fails, the entire job is rescheduled. For fine‑grained resilience (task‑level recomputation), the checkpoint protocol would need to be per‑task and the scheduler would need to track individual task liveness. The coarse‑grained approach simplifies recovery.
- Centralized Bottleneck: The leader scheduler may become a scalability limit. In production, the cluster can be partitioned into “cells” each with its own scheduler, and a‑top‑level orchestrator handles cross‑cell preemption only rarely.
Comparison to Existing Systems
- Apache YARN: Supports preemption (via capacity scheduler) but lacks integrated checkpoint management; jobs must handle recovery themselves.
- Kubernetes: Supports checkpointing via container runtime interfaces and has discretionary preemption (via Pod priorities), but a unified lease‑based model for long jobs is not standard.
- HPC Batch Systems (e.g., Slurm): Offer preemptible jobs and checkpointing, but often as separate mechanisms. Our design tightly couples leases, checkpoints, and preemption.
Limitations
- Non‑cooperative jobs that ignore preemption signals will be force‑killed after the grace period, losing any in‑memory state. The system assumes jobs implement the checkpoint protocol.
- Checkpoint storage pressure: Retaining many checkpoints can consume significant storage. A retention policy (keep last N or total size limit) should be enforced by the Checkpoint Registry.
- Network partitions could isolate the scheduler leader. Raft tolerates minority partitions; the majority partition continues. Clients in a minority partition may be unable to submit jobs until connectivity is restored.
9. Conclusion
This design provides a robust foundation for scheduling long‑running jobs in dynamic environments. By combining leases, checkpoints, and preemption—and making the scheduler itself fault‑tolerant—it achieves high utilization while protecting jobs from disruptive preemptions and failures. The modular architecture allows independent evolution of components (e.g., different checkpointing schemes or preemption policies) and can be scaled to large clusters with appropriate partitioning.