Disk Scheduling Algorithms SCAN SSTF: OS Algorithm Deep Dive

Operating System Algorithms By Michael Chen, Distinguished Engineer 25 min read

Introduction and Core Concepts

Disk scheduling is a fundamental function of operating systems that determines the order in which pending disk I/O requests are serviced. In systems with rotating magnetic hard disk drives (HDDs), the time required to access data is dominated by mechanical movement: the seek time to move the read/write head to the correct cylinder, rotational latency to wait for the desired sector, and transfer time to actually read or write data. Because seek time is by far the most significant component, the order in which requests are processed has a profound impact on overall system throughput, average response time, and fairness.

Modern operating systems maintain a queue of pending disk requests when processes generate I/O faster than the disk can service them. Without a scheduling policy, these requests would be served in First-Come, First-Served (FCFS) order, which is simple but often highly inefficient due to excessive head movement. Disk scheduling algorithms were developed to optimize this queue, minimizing total head movement and improving efficiency. Among the most important and widely studied algorithms are Shortest Seek Time First (SSTF) and SCAN, often called the elevator algorithm. Understanding disk scheduling algorithms scan sstf is essential for grasping how operating systems balance performance, starvation, and predictability in I/O subsystems.

SSTF and SCAN represent two fundamentally different philosophies. SSTF is a greedy algorithm that always selects the request closest to the current head position, minimizing immediate seek time. SCAN, in contrast, imposes a directional sweep pattern, moving the head in one direction servicing all requests in its path until it reaches the end of the disk, then reversing direction. While SSTF can achieve excellent average seek times, it is prone to starvation. SCAN sacrifices some immediate optimality to provide more uniform waiting times and prevent starvation. Both algorithms remain critical teaching tools and continue to influence scheduling in HDDs, RAID arrays, and even in analogous domains like elevator control and network packet scheduling.

Why Disk Scheduling Still Matters

Although Solid State Drives (SSDs) have largely eliminated mechanical seek time in consumer devices, disk scheduling remains highly relevant. Enterprise storage, archival systems, surveillance storage, and budget NAS devices still rely heavily on HDDs where scheduling is critical. Furthermore, the principles behind SCAN and SSTF — greedy nearest-neighbor selection versus directional sweeping to ensure fairness — appear in many other OS scheduling problems, including CPU scheduling, I/O request merging in the Linux block layer, and database query optimization for disk-resident data.

From a performance perspective, a poor scheduling choice can increase average seek time by an order of magnitude. For example, a random FCFS workload on a disk with 200 cylinders might require an average seek of 66 cylinders per request, while SSTF or SCAN can often reduce this to under 30 cylinders under the same load. In high-throughput servers handling thousands of concurrent I/O operations per second, this difference directly translates to latency, IOPS, and user-perceived responsiveness.

How It Works

To understand SSTF and SCAN, we must first define the core model. Consider a disk with cylinders numbered from 0 to C-1 (for example, 0 to 199). The disk head starts at an initial position, and a queue of requests arrives, each requesting access to a specific cylinder. The goal is to compute an order to service these requests that optimizes a metric, typically total head movement or average waiting time. The head can only move sequentially from cylinder to cylinder, and the cost of moving from cylinder a to cylinder b is |a - b|.

Shortest Seek Time First (SSTF) Mechanism

SSTF operates like Shortest Job First (SJF) in CPU scheduling. At each step, the algorithm examines all pending requests and selects the one with the minimum seek distance from the current head position. After servicing that request, the head position is updated, and the process repeats until the queue is empty. This is a greedy, dynamic policy — the next choice depends entirely on the current head location, not on arrival order or direction.

The advantage of SSTF is its low average seek time. By always picking the nearest request, it minimizes incremental movement and generally outperforms FCFS by a large margin. However, its major drawback is starvation. If a steady stream of requests arrives near the current head position, a request for a distant cylinder may be deferred indefinitely. SSTF also suffers from higher variance in response time; some requests are serviced almost immediately while others wait a long time, leading to unpredictable performance. Additionally, SSTF can cause the head to oscillate around a busy region, which is efficient locally but unfair globally.

SCAN (Elevator Algorithm) Mechanism

SCAN was designed to provide better fairness and eliminate starvation while still reducing seek time compared to FCFS. The algorithm is analogous to an elevator: the head moves continuously in one direction (say, toward higher-numbered cylinders), servicing all requests in its path. When it reaches the highest-numbered end of the disk (or the highest pending request, depending on the variant), it reverses direction and sweeps back toward the lowest end, again servicing requests along the way.

This directional sweep ensures that every request will eventually be serviced within at most one full sweep plus a reversal. No request can starve indefinitely because the head is guaranteed to pass over every cylinder in both directions. The trade-off is that requests just behind the head after it passes must wait for a full reversal, which can increase their waiting time compared to SSTF. SCAN also exhibits a non-uniform waiting time pattern: requests near the middle of the disk are serviced more frequently than those at the edges in some variants, though the overall variance is much lower than SSTF. There are two common interpretations: the strict SCAN goes all the way to cylinder 0 and C-1 regardless of requests, while LOOK (a common optimization) only goes as far as the furthest pending request in each direction.

Key Terminology

Understanding these algorithms requires familiarity with a few terms. Seek Time is the time to move the head to the target cylinder. Seek Distance is the number of cylinders traversed. Starvation occurs when a request is indefinitely postponed. Throughput is the number of requests serviced per unit time, and Average Waiting Time is the mean time a request spends in the queue. Both SSTF and SCAN aim to optimize these metrics under different constraints.

Implementation

Implementing SSTF and SCAN in software is straightforward but requires careful handling of sorting, direction, and edge cases. Below are clean, well-commented Python implementations that can be used for simulation, OS coursework, or I/O subsystem prototyping. Note that these implementations assume all requests are available at the start (a static queue) for simplicity; a real OS implementation would handle dynamic arrivals with a priority queue or sorted list.

SSTF Implementation

This implementation repeatedly finds the closest request to the current head. It uses a simple linear scan for clarity; for large queues, a balanced BST or heap keyed by distance would be more efficient.

def sstf(requests, initial_head):
    """
    Shortest Seek Time First disk scheduling.
    requests: list of cylinder numbers
    initial_head: starting head position
    Returns: (service_order, total_movement)
    """
    pending = requests.copy()
    head = initial_head
    service_order = []
    total_movement = 0

    while pending:
        # Find request with minimum seek distance
        min_distance = float('inf')
        next_index = -1
        for i, req in enumerate(pending):
            distance = abs(req - head)
            if distance < min_distance:
                min_distance = distance
                next_index = i
        
        # Service the closest request
        next_req = pending.pop(next_index)
        total_movement += abs(next_req - head)
        head = next_req
        service_order.append(next_req)
    
    return service_order, total_movement

# Example usage
requests = [82, 170, 43, 140, 24, 16, 190]
head = 50
order, movement = sstf(requests, head)
print(f"SSTF Order: {order}")  # Output depends on head
print(f"Total head movement: {movement}")

SCAN Implementation

SCAN requires sorting the requests and handling direction. This version implements the classic SCAN that goes to the disk ends (0 and max_cylinder), and supports both initial directions.

def scan(requests, initial_head, max_cylinder=199, direction="right"):
    """
    SCAN (Elevator) disk scheduling.
    direction: "right" means toward higher cylinders, "left" toward 0
    max_cylinder: highest cylinder number on disk
    """
    if not requests:
        return [], 0

    sorted_reqs = sorted(requests)
    head = initial_head
    service_order = []
    total_movement = 0

    # Partition requests into left and right of head
    left = [r for r in sorted_reqs if r < head]
    right = [r for r in sorted_reqs if r >= head]

    if direction == "right":
        # Service right side in ascending order
        for req in right:
            total_movement += abs(req - head)
            head = req
            service_order.append(req)
        # Go to end if not already there
        if head != max_cylinder:
            total_movement += abs(max_cylinder - head)
            head = max_cylinder
        # Reverse and service left side in descending order
        for req in reversed(left):
            total_movement += abs(req - head)
            head = req
            service_order.append(req)
    else:  # direction == "left"
        for req in reversed(left):
            total_movement += abs(req - head)
            head = req
            service_order.append(req)
        if head != 0:
            total_movement += abs(head - 0)
            head = 0
        for req in right:
            total_movement += abs(req - head)
            head = req
            service_order.append(req)

    return service_order, total_movement

# Example: head at 50, moving right
order, movement = scan([82, 170, 43, 140, 24, 16, 190], 50, 199, "right")
print(f"SCAN Order: {order}")
print(f"Total movement: {movement}")

LOOK Optimization (SCAN without going to disk ends)

LOOK is a practical optimization that avoids unnecessary travel to the disk ends. It only goes as far as the last request in each direction.

def look(requests, initial_head, direction="right"):
    """
    LOOK algorithm - SCAN without traveling to disk ends.
    More efficient than SCAN when requests are clustered.
    """
    if not requests:
        return [], 0

    sorted_reqs = sorted(requests)
    head = initial_head
    service_order = []
    total_movement = 0

    left = [r for r in sorted_reqs if r < head]
    right = [r for r in sorted_reqs if r >= head]

    if direction == "right":
        for req in right:
            total_movement += abs(req - head)
            head = req
            service_order.append(req)
        for req in reversed(left):
            total_movement += abs(req - head)
            head = req
            service_order.append(req)
    else:
        for req in reversed(left):
            total_movement += abs(req - head)
            head = req
            service_order.append(req)
        for req in right:
            total_movement += abs(req - head)
            head = req
            service_order.append(req)

    return service_order, total_movement

Simulation Harness for Comparison

A useful tool for studying these algorithms is a harness that compares total movement and average waiting time across policies.

def simulate_all(requests, head, max_cylinder=199):
    """
    Compare FCFS, SSTF, SCAN, and LOOK on the same workload.
    """
    def fcfs(reqs, h):
        movement = 0
        curr = h
        for r in reqs:
            movement += abs(r - curr)
            curr = r
        return reqs, movement

    results = {}
    results['FCFS'] = fcfs(requests, head)
    results['SSTF'] = sstf(requests, head)
    results['SCAN'] = scan(requests, head, max_cylinder, "right")
    results['LOOK'] = look(requests, head, "right")

    print(f"Initial head: {head}, Requests: {requests}")
    for name, (order, movement) in results.items():
        avg_seek = movement / len(requests) if requests else 0
        print(f"{name:6} -> Order: {order}, Total: {movement}, Avg: {avg_seek:.2f}")

# Run simulation
simulate_all([82, 170, 43, 140, 24, 16, 190], 50)

Step-by-Step Example

Let us walk through a concrete example to illustrate the behavioral difference between SSTF and SCAN. Assume a disk with cylinders 0-199, initial head position at 50, and a pending queue with 7 requests: [82, 170, 43, 140, 24, 16, 190]. We will assume the SCAN algorithm is moving initially toward higher cylinder numbers (to the right).

SSTF Walkthrough

SSTF always picks the nearest request. Starting at 50, the distances are: 82 (32), 170 (120), 43 (7), 140 (90), 24 (26), 16 (34), 190 (140). The closest is 43 (distance 7). The head moves 50 -> 43, total movement = 7.

Now at 43, remaining requests are [82, 170, 140, 24, 16, 190]. Distances from 43: 82 (39), 170 (127), 140 (97), 24 (19), 16 (27), 190 (147). The closest is 24 (distance 19). Head moves 43 -> 24, total = 26.

At 24, remaining [82, 170, 140, 16, 190]. Distances: 82 (58), 170 (146), 140 (116), 16 (8), 190 (166). Closest is 16 (distance 8). Head moves 24 -> 16, total = 34.

At 16, remaining [82, 170, 140, 190]. Distances: 82 (66), 170 (154), 140 (124), 190 (174). Closest is 82 (distance 66). Head moves 16 -> 82, total = 100.

At 82, remaining [170, 140, 190]. Distances: 170 (88), 140 (58), 190 (108). Closest is 140 (distance 58). Head moves 82 -> 140, total = 158.

At 140, remaining [170, 190]. Distances: 170 (30), 190 (50). Closest is 170 (distance 30). Head moves 140 -> 170, total = 188. Finally, 170 -> 190 (20), total = 208. The final SSTF service order is [43, 24, 16, 82, 140, 170, 190] with total head movement of 208 cylinders.

SCAN Walkthrough

SCAN moving right from 50 first sorts the requests: [16, 24, 43, 82, 140, 170, 190]. It partitions them into left (<50): [16, 24, 43] and right (>=50): [82, 140, 170, 190]. It services the right side in ascending order.

Head at 50 -> 82 (32), total = 32. 82 -> 140 (58), total = 90. 140 -> 170 (30), total = 120. 170 -> 190 (20), total = 140. Now it has reached the last request on the right. In strict SCAN, it would continue to cylinder 199 (9 more), total = 149, then reverse. In LOOK, it reverses immediately. Let us follow strict SCAN: head at 190 -> 199 (9), total = 149.

Now reversing direction, it services the left side in descending order: 199 -> 43 (156), total = 305. 43 -> 24 (19), total = 324. 24 -> 16 (8), total = 332. The SCAN service order is [82, 140, 170, 190, 43, 24, 16] with total movement 332 (including travel to the end). LOOK would have total 208 + (190-43)?? Actually LOOK would be 82-140-170-190-43-24-16 = 140 + 166 = 306, saving the 9+? travel to the end. This example clearly shows SSTF's lower total movement (208 vs 332) but also its non-directional, potentially starving behavior, while SCAN provides a predictable sweep.

This walkthrough highlights a key insight: total head movement alone does not tell the whole story. While SSTF is more efficient here, if new requests continuously arrived near 140-170, a request at 16 could starve under SSTF but would be guaranteed service within one SCAN sweep.

Complexity Analysis

Analyzing the time and space complexity of disk scheduling algorithms requires distinguishing between the scheduling decision overhead and the resulting disk performance (total seek time). The algorithmic complexity refers to the CPU time needed to select the next request, while the performance metric is the total head movement, which depends on the request distribution.

For SSTF, each scheduling decision requires finding the minimum distance among n pending requests. A naive linear scan takes O(n) per decision, leading to O(n²) total time to schedule n requests. If the pending queue is maintained in a balanced binary search tree sorted by cylinder, or if we use two heaps for left and right, we can find the nearest request in O(log n) time per decision, yielding O(n log n) total. However, the constant factors and implementation complexity increase. Space complexity is O(n) to store the queue.

For SCAN and LOOK, the dominant cost is sorting the request queue, which takes O(n log n) time. Once sorted, servicing requests is a linear scan O(n). Therefore, total time is O(n log n). Space is also O(n) for the sorted list and partitions. In practice, SCAN's overhead is often lower than SSTF's naive O(n²) because sorting is highly optimized, and the sweep pattern is simple to implement in firmware.

From a disk performance perspective, worst-case total head movement for both algorithms can be O(n * C) where C is the number of cylinders, but average-case behavior differs. SSTF's average seek distance is typically lower than SCAN's under random workloads, but its worst-case waiting time for a single request is unbounded (starvation), while SCAN's worst-case waiting time is bounded by approximately 2*C.

Operation / Metric Best Case Average Case Worst Case Space
SSTF Scheduling (naive scan) O(n²) O(n²) O(n²) O(n)
SSTF Scheduling (BST/Heap optimized) O(n log n) O(n log n) O(n log n) O(n)
SCAN / LOOK Scheduling (sorting) O(n log n) O(n log n) O(n log n) O(n)
SSTF Total Head Movement O(n) O(n * sqrt(C)) approx. O(n * C) (starvation possible) -
SCAN Total Head Movement O(C) O(C + n) O(2 * C) -
FCFS Total Head Movement (baseline) O(n) O(n * C/3) O(n * C) O(n)

It is important to note that best/average/worst for head movement depend heavily on workload. If requests are already sorted and clustered near the head, both SSTF and SCAN achieve near-optimal movement. If requests are adversarially distributed, SSTF can be forced into many small moves followed by a huge jump, while SCAN's movement remains bounded by the disk size.

Variations and Optimizations

Both SSTF and SCAN have spawned numerous variants designed to address their weaknesses and adapt to modern storage architectures. Understanding these optimizations is crucial for system designers who must tune I/O schedulers for specific workloads.

C-SCAN and C-LOOK (Circular Variants)

Standard SCAN services requests in both directions, which leads to non-uniform waiting times: the area just behind the head after a reversal waits longer. Circular SCAN (C-SCAN) addresses this by treating the disk as circular. The head moves only in one direction, servicing requests along the way. When it reaches the end, it quickly returns (without servicing) to the beginning and continues. This provides more uniform waiting time, as each cylinder is visited at a regular interval, at the cost of extra return movement. C-LOOK is the optimized version that only goes as far as the last request before jumping back, eliminating the wasted travel to the disk ends. C-SCAN is widely used in systems where fairness and predictable latency are more important than raw throughput.

LOOK and C-LOOK Optimizations

As mentioned, LOOK and C-LOOK avoid traveling to the physical disk ends if there are no requests there. This simple change can save significant seek time when the workload is clustered in the middle of the disk. For example, if all requests are between cylinders 50 and 100 on a 0-199 disk, SCAN would waste 100 cylinders of movement going to 0 and 199, while LOOK would only sweep between 50 and 100. Most modern implementations use LOOK rather than strict SCAN for this reason, and the Linux kernel's deadline and CFQ schedulers incorporate LOOK-like logic.

SSTF Optimizations and Aging

To combat starvation in SSTF, aging can be introduced. Each request is assigned a priority that increases with its waiting time. The scheduler then selects the request with the lowest combined score of seek distance and aging penalty, or it promotes long-waiting requests after a threshold. Another approach is to implement a bounded SSTF or use a window: service the closest request within a certain distance, but if a request has waited longer than a timeout, service it next regardless of distance. Hybrid algorithms like FSCAN use two queues: one queue is serviced via SCAN while new arrivals go to the other queue, preventing new requests from indefinitely delaying old ones.

Modern I/O Scheduler Adaptations

In contemporary operating systems, pure SSTF or SCAN is rarely used alone. Instead, schedulers like Linux's BFQ (Budget Fair Queuing), deadline, and kyber combine ideas from these algorithms with additional concerns: read/write prioritization (reads are often latency-sensitive), request merging (adjacent requests are coalesced), and quality-of-service guarantees. For instance, the deadline scheduler imposes expiration times on requests to prevent starvation, effectively combining SCAN's directional sweep with SSTF-like seek optimization within deadlines. For SSDs, schedulers focus less on seek distance and more on parallelism and write amplification, but the queuing and fairness concepts remain.

Real-World Applications

While the classic textbook example is a single HDD in a desktop computer, the principles of SCAN and SSTF appear in a surprisingly wide range of real-world systems, from large-scale data centers to embedded devices.

Enterprise Storage and RAID Arrays

In enterprise storage area networks (SANs) and network-attached storage (NAS) that still employ large HDD pools, disk scheduling directly impacts IOPS and tail latency. Database servers running OLTP workloads generate highly random I/O patterns where SSTF-like optimizations can significantly boost throughput. However, for multi-tenant cloud storage where fairness between tenants is critical, SCAN or C-SCAN variants are preferred to prevent one tenant's sequential workload from starving another's random requests. RAID controllers often implement their own scheduling layer, reordering requests across multiple disks to minimize overall seek time while maintaining redundancy.

Operating System I/O Schedulers

The Linux kernel has evolved through several I/O schedulers, each inspired by these algorithms. The original elevator scheduler was a direct implementation of SCAN/LOOK. The deadline scheduler adds expiration timers to SCAN to guarantee latency bounds. The Completely Fair Queuing (CFQ) scheduler provides per-process fairness using time slices combined with SCAN-like ordering within each process's queue. Even the newer multiqueue schedulers (blk-mq) for NVMe still use request sorting and merging concepts derived from SCAN. Windows and macOS similarly reorder disk requests in their storage stacks to optimize for HDDs when present.

Analogous Domains: Elevators, Robotics, and Networks

The SCAN algorithm is literally called the elevator algorithm because it models how elevators service floor requests. This analogy is not just pedagogical; elevator control systems in high-rise buildings use SCAN, LOOK, and C-SCAN logic to minimize waiting time and energy. Similarly, in robotics, a robotic arm picking items from a conveyor or a 3D printer head moving across a bed benefits from sweep-based scheduling to minimize travel. In networking, disk scheduling concepts appear in token ring and polling systems where a controller sweeps through nodes. Even in web servers and databases, request batching and reordering to improve disk locality (for example, when serving large media files or performing table scans) uses SSTF-like nearest-neighbor heuristics.

Application Domain Preferred Algorithm Reasoning Example System
Single-User Desktop HDD SSTF / LOOK Maximize throughput, low starvation risk with light load Legacy Windows HDD defragmentation
Multi-Tenant Cloud Storage C-SCAN / C-LOOK Uniform waiting time, fairness across tenants Ceph, Amazon EBS (HDD tiers)
Database OLTP Server SSTF with Aging Low average seek, aging prevents starvation of old transactions PostgreSQL on RAID 10 HDD
Video Surveillance Storage SCAN Sequential writes + periodic reads, predictable sweep NVR with 24x HDD array
Elevator Control System SCAN / LOOK Physical sweep model, passenger fairness High-rise building elevator controller
Linux I/O Scheduler (blk-mq) Hybrid (Deadline + SCAN) Balance latency guarantees with seek optimization Linux kernel 5.x+ BFQ/Deadline

Comparison with Alternatives

SSTF and SCAN do not exist in isolation. They are part of a broader family of disk scheduling policies, each with distinct trade-offs in terms of throughput, fairness, implementation complexity, and starvation behavior. Choosing the right algorithm depends on workload characteristics and system goals.

First-Come, First-Served (FCFS) is the simplest policy: requests are serviced in arrival order. It is fair and starvation-free but has poor throughput due to random seek patterns. SSTF improves throughput dramatically but risks starvation. SCAN balances throughput and fairness but can still exhibit non-uniform waiting times. C-SCAN improves uniformity at the cost of extra seek distance on the return jump. LOOK and C-LOOK are strictly better than SCAN and C-SCAN in terms of total movement because they avoid unnecessary edge travel, and are therefore almost always preferred in practice. More advanced algorithms like FSCAN (using two queues) and N-Step-SCAN (servicing N requests per sweep) further bound starvation by limiting how long new requests can delay old ones.

For SSDs, none of these seek-optimizing algorithms are appropriate, as seek time is negligible. Instead, schedulers for SSDs focus on parallelism, write coalescing, and wear leveling. However, even on SSDs, request merging and sorting can still improve performance by reducing command overhead and maximizing sequential access patterns for the flash translation layer.

Feature FCFS SSTF SCAN / LOOK C-SCAN / C-LOOK
Throughput (IOPS) Low High (best avg seek) Medium-High Medium
Average Seek Time High Lowest Moderate Moderate-High
Starvation Risk None High Low Very Low
Variance in Waiting Time Low High Moderate Low (uniform)
Implementation Complexity O(1) - queue O(n²) naive, O(n log n) optimized O(n log n) sort O(n log n) sort + jump
Fairness Perfect (arrival order) Poor Good Excellent
Best Use Case Light load, simplicity needed Batch systems, throughput priority General purpose HDD Real-time, multi-tenant, elevator
Direction Handling None None (greedy) Bidirectional sweep Unidirectional circular

In summary, if your primary goal is raw throughput and starvation is unlikely (light or batch workloads), SSTF is attractive. If you need predictable latency and fairness, especially under heavy or continuous load, SCAN/LOOK or C-SCAN/C-LOOK is superior. Most production systems today use LOOK or C-LOOK as the base, augmented with deadlines or aging to provide hard latency guarantees, effectively getting the best of both worlds.

Common Mistakes and Best Practices

Implementing or configuring disk scheduling incorrectly can lead to worse performance than FCFS, or to subtle bugs like starvation and deadlock. Here are common pitfalls and how to avoid them.

Pitfall 1: Ignoring Direction and Initial Head Position

A frequent mistake in SCAN implementations is to assume the head always starts moving right, or to forget to handle the case where the head is at the disk edge. The initial direction should be configurable or based on the previous movement to avoid unnecessary reversals. Always validate that the head position is within [0, max_cylinder] and handle empty left or right partitions gracefully. Failing to do so can cause incorrect total movement calculations or missed requests.

Pitfall 2: Using Strict SCAN Instead of LOOK

Students and even some system implementers default to strict SCAN that travels to the physical disk ends (0 and max_cylinder) even when no requests exist there. This wastes seek time and energy. Best practice is to use LOOK or C-LOOK unless the hardware specifically requires a full sweep for calibration. Always check whether your variant should include the extra travel to the ends, and document the choice. In performance-critical code, this optimization alone can reduce average seek time by 10-20% for clustered workloads.

Pitfall 3: Starvation in SSTF Without Mitigation

Deploying pure SSTF in a system with continuous request arrivals is dangerous. A common error is to benchmark SSTF on a static queue and assume it will perform well dynamically. In production, you must implement aging, timeouts, or a hybrid approach like FSCAN. A best practice is to set a maximum waiting time threshold: if a request has waited longer than, say, 100ms, promote it to the front of the queue regardless of distance. This bounds tail latency while preserving most of SSTF's throughput benefits.

Pitfall 4: Not Merging Adjacent Requests

Disk schedulers should merge contiguous or overlapping requests before scheduling. For example, requests for cylinders 50, 51, and 52 can be coalesced into a single larger request, reducing overhead and allowing more efficient transfer. Neglecting this step leads to unnecessary head movements and missed optimization opportunities. Modern OS schedulers perform request merging as a first pass before applying SCAN/SSTF ordering.

Best Practices Summary

Interview Questions

Disk scheduling algorithms are a favorite topic in operating system interviews for software engineering, systems, and SRE roles. Below are common questions with concise, interview-ready answers that demonstrate deep understanding.

Q1: What is the difference between SSTF and SCAN, and when would you choose one over the other?

Answer: SSTF is a greedy algorithm that always services the closest request to the current head, minimizing immediate seek time and achieving high throughput but risking starvation and high variance. SCAN moves the head in one direction servicing requests along the way, then reverses at the disk end, providing bounded waiting time and fairness at the cost of slightly higher average seek. Choose SSTF when throughput is paramount and load is light or batch-oriented with low starvation risk. Choose SCAN/LOOK for general-purpose or multi-tenant systems where fairness, predictability, and starvation avoidance are critical. In practice, most systems use LOOK or hybrid deadline-based schedulers that combine both ideas.

Q2: Can SSTF cause starvation? Give an example and explain how to fix it.

Answer: Yes. Suppose the head is at cylinder 50 and a request at cylinder 10 is pending, but a continuous stream of requests arrives near 50-60. SSTF will always prefer the nearby requests, deferring the request at 10 indefinitely. This is starvation. Fixes include aging (increasing priority with waiting time), setting a maximum waiting time after which a request is forced to be serviced, or using a two-queue algorithm like FSCAN where new arrivals wait in a separate queue while the current queue is serviced via SCAN. In Linux, the deadline scheduler solves this by assigning expiration times to requests.

Q3: What is the difference between SCAN and LOOK, and between SCAN and C-SCAN?

Answer: SCAN goes all the way to the physical disk ends (0 and max cylinder) before reversing, even if no requests are at the extremes. LOOK only goes as far as the furthest pending request in each direction, saving unnecessary movement and is strictly more efficient. C-SCAN (Circular SCAN) moves only in one direction; after reaching the end, it jumps back to the start without servicing on the return, providing uniform waiting time. SCAN services in both directions. C-LOOK is the optimized circular version that jumps back from the last request rather than the disk end. LOOK/C-LOOK are almost always preferred over SCAN/C-SCAN in practice.

Q4: What is the time complexity of SSTF and SCAN? How would you implement SSTF efficiently?

Answer: Naive SSTF scans all n pending requests to find the closest each time, taking O(n) per request and O(n²) total. An optimized SSTF can maintain requests in a balanced BST sorted by cylinder, allowing O(log n) to find the predecessor and successor of the head, then picking the closer, for O(n log n) total. SCAN/LOOK sorts the requests once in O(n log n) and then linearly sweeps in O(n), so total is O(n log n). Space for both is O(n). For implementation, I would sort requests, partition into left and right of head, and for SSTF use two heaps or a sorted container; for SCAN, simply iterate through the sorted partitions in direction order.

Q5: How does disk scheduling change for SSDs versus HDDs?

Answer: For HDDs, seek time dominates, so minimizing head movement via SSTF/SCAN is crucial. For SSDs, there is no mechanical head; access time is uniform and dominated by electronic latency, parallelism, and erase/write cycles. Therefore, seek-optimizing algorithms provide little benefit. SSD schedulers instead focus on maximizing parallelism across flash channels, coalescing writes to reduce write amplification, wear leveling, and prioritizing reads over writes for latency. However, request merging and sorting can still help by reducing command overhead and improving sequentiality for the flash translation layer. Modern OSes detect the device type and select an appropriate scheduler (e.g., noop or kyber for SSDs vs. BFQ/deadline for HDDs).

Frequently Asked Questions

What is Disk Scheduling Algorithms Scan Sstf and how does it work?

Disk Scheduling Algorithms Scan Sstf is a fundamental concept in computer science. It involves specific techniques and data organization methods designed to solve computational problems efficiently. Understanding the core mechanics helps developers choose the right approach for their applications.

What is the time complexity of Disk Scheduling Algorithms Scan Sstf?

The time complexity of Disk Scheduling Algorithms Scan Sstf varies depending on the specific operation and implementation. Common complexities range from O(1) constant time for basic operations to O(n log n) or O(n²) for more complex operations. The article above provides detailed complexity analysis for each operation.

When should I use Disk Scheduling Algorithms Scan Sstf in my projects?

Use Disk Scheduling Algorithms Scan Sstf when your application requires the specific performance characteristics it provides. Consider factors like data size, operation frequency, memory constraints, and whether the problem domain matches the strengths of Disk Scheduling Algorithms Scan Sstf. The real-world applications section above covers common use cases.

What are the advantages and disadvantages of Disk Scheduling Algorithms Scan Sstf?

The main advantages of Disk Scheduling Algorithms Scan Sstf include efficient performance for its target use cases and well-understood theoretical guarantees. Disadvantages may include implementation complexity, memory overhead, or performance limitations in certain edge cases. Always benchmark against alternatives for your specific workload.

How does Disk Scheduling Algorithms Scan Sstf compare to its alternatives?

Disk Scheduling Algorithms Scan Sstf offers distinct trade-offs compared to alternative approaches. While it excels in certain scenarios, other algorithms or data structures may be better suited for different problem constraints. The comparison table in the article provides a detailed analysis of these trade-offs.