AlgoTales · Roadmap

Real-world applications

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Queues show up wherever many requests want the same limited resource, such as a printer, a worker, a server or a call agent. Lining requests up keeps things fair and stops the resource being overwhelmed, which is why queues are everywhere in real software.

Practical use cases

  • Web app: Sending emails in Laravel queues. When a customer places an order, the page should not wait while the confirmation email is sent. The app puts an "email job" in a queue and replies at once. A background worker takes jobs from the front, so the checkout feels instant even during a sale.
  • Web app: Ticket booking with a virtual waiting room. When a popular show opens for booking, thousands of users arrive in the same second. A waiting room puts them in a queue and lets in a few hundred at a time. The booking system stays up, and people are admitted in a fair arrival order.
  • System: Message brokers and schedulers. Message queue systems such as RabbitMQ and SQS pass work between services in order, so one service can be slow without breaking another. Operating systems also queue programs waiting for the processor.

The story: The One Printer in the Coaching Centre

Brightpath Coaching Centre had one printer and sixty students. Every evening, chaos: Kabir would send a 40-page worksheet, then Zoya's single-page permission slip got stuck behind it, and the teacher's test papers somehow jumped ahead of everyone.

The centre's IT teacher, Mr. Dutta, fixed it with one idea: a queue. Each print request joined the back of the line and the printer always took the one at the front. The wait was fair and everyone could see roughly when their turn would come.

Mira, visiting her cousin, noticed that queues were everywhere once you looked: the line at the railway booking counter, the song playlist on her phone, messages waiting to be delivered on WhatsApp. "Mr. Dutta, your fix is not just for printers. Anything where things arrive faster than they can be handled needs a queue." Even the printer could share its time fairly: every job prints a little, then goes to the back so that long jobs do not block short ones. That is called round robin, and our code runs exactly that.

How to spot this problem, and where you need it

Work arrives in bursts and the part of the system that does it is slower or limited, so requests time out, pile up in memory, or make the user wait for something they do not need to wait for.

Signs you need it

  • A page is slow because it does extra work after the user's action, like sending emails, resizing images or generating PDFs.
  • Traffic spikes make the server crash or time out, although the average load is fine.
  • The requirement mentions "process later", "background", "in order of arrival" or "do not lose any request".

Where to use it in a project

  • Laravel or other framework job queues for emails, notifications, exports and image processing.
  • Booking, ticketing and flash-sale systems that need a fair waiting room.
  • Splitting a big system into services that talk through a message broker.

The solution

Do not do slow work inside the user's request. Put a small description of the work into a queue and answer the user straight away. Run one or more workers that take jobs from the front and process them at a steady pace, retrying failed ones. The queue absorbs bursts, keeps order and survives restarts if stored in a database or Redis.

Payoff: Before: checkout took 6 seconds because it sent the email in the same request. After: checkout responds in under half a second and the email follows moments later.

Explain it like I am 8

Whenever many people want the same thing but only one can have it at a time, we line them up. A queue is how a computer says "wait for your turn, and the one who came first goes first".

How it works, step by step

  1. Spot the pattern: work arrives, one worker handles it, and order of arrival matters.
  2. Enqueue each new job at the back.
  3. Dequeue from the front when the worker is free.
  4. For fair sharing, let each job run for a short turn (a quantum). If it is not finished, enqueue it again at the back.
  5. Repeat until the queue is empty. Nobody starves and short jobs finish soon.

The code in four languages

PHP

<?php
// Round-robin printing: each job prints up to $quantum pages per turn.
function roundRobin(array $jobs, int $quantum): array {
    $queue = new SplQueue();
    foreach ($jobs as $name => $pages) $queue->enqueue([$name, $pages]);
    $order = [];
    while (!$queue->isEmpty()) {
        [$name, $left] = $queue->dequeue();            // front of the line
        $left -= min($quantum, $left);                 // print one turn
        $order[] = $name;
        if ($left > 0) $queue->enqueue([$name, $left]); // not finished: back of the line
    }
    return $order;
}

$order = roundRobin(['A' => 5, 'B' => 2, 'C' => 4], 2);
echo implode(' -> ', $order) . "\n";   // A -> B -> C -> A -> C -> A

JavaScript

// Round-robin printing: each job prints up to quantum pages per turn.
function roundRobin(jobs, quantum) {
  const queue = Object.entries(jobs);      // [name, pagesLeft] pairs
  let head = 0;                            // moving a pointer avoids slow shift()
  const order = [];
  while (head < queue.length) {
    const [name, pages] = queue[head++];   // front of the line
    const left = pages - Math.min(quantum, pages);   // print one turn
    order.push(name);
    if (left > 0) queue.push([name, left]);          // not finished: back of the line
  }
  return order;
}

const order = roundRobin({ A: 5, B: 2, C: 4 }, 2);
console.log(order.join(' -> '));   // A -> B -> C -> A -> C -> A

Java

import java.util.*;

public class Main {
    record Job(String name, int pagesLeft) {}

    // Round-robin printing: each job prints up to quantum pages per turn.
    static List<String> roundRobin(Map<String, Integer> jobs, int quantum) {
        Queue<Job> queue = new ArrayDeque<>();
        jobs.forEach((name, pages) -> queue.add(new Job(name, pages)));
        List<String> order = new ArrayList<>();
        while (!queue.isEmpty()) {
            Job job = queue.poll();                              // front of the line
            int left = job.pagesLeft() - Math.min(quantum, job.pagesLeft());   // print one turn
            order.add(job.name());
            if (left > 0) queue.add(new Job(job.name(), left));  // not finished: back of the line
        }
        return order;
    }

    public static void main(String[] args) {
        Map<String, Integer> jobs = new LinkedHashMap<>();       // keeps A, B, C in order
        jobs.put("A", 5);
        jobs.put("B", 2);
        jobs.put("C", 4);
        List<String> order = roundRobin(jobs, 2);
        System.out.println(String.join(" -> ", order));          // A -> B -> C -> A -> C -> A
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

type job struct {
	name      string
	pagesLeft int
}

// roundRobin prints in turns: each job prints up to quantum pages per turn.
func roundRobin(jobs []job, quantum int) []string {
	queue := append([]job(nil), jobs...)
	head := 0 // moving a pointer avoids copying the slice on every dequeue
	var order []string
	for head < len(queue) {
		j := queue[head] // front of the line
		head++
		left := j.pagesLeft - min(quantum, j.pagesLeft) // print one turn
		order = append(order, j.name)
		if left > 0 { // not finished: back of the line
			queue = append(queue, job{j.name, left})
		}
	}
	return order
}

func main() {
	order := roundRobin([]job{{"A", 5}, {"B", 2}, {"C", 4}}, 2)
	fmt.Println(strings.Join(order, " -> ")) // A -> B -> C -> A -> C -> A
}

Time: O(1) per enqueue/dequeue · Extra space: O(n). The queue holds at most all n waiting jobs, and each line-up or serve is a constant-time step.

Watch out for

  • Using an array with array_shift/shift for a big queue: it can shift every item. Use SplQueue in PHP or a head pointer in JavaScript.
  • Reaching for a queue when order should depend on importance. That is a priority queue.
  • Letting a queue grow forever with no limit: if work arrives faster than it is handled, memory runs out.

Quick check

  1. Which real situation is naturally a queue?
    • Orders waiting for a delivery rider in arrival order
    • Undo history in a text editor
    • Browser back button
  2. In round robin, what happens to a job that is not finished after its turn?
    • It is cancelled
    • It jumps to the front
    • It goes to the back of the queue
  3. Which famous search uses a queue to explore level by level?
    • Depth-first search
    • Binary search
    • Breadth-first search