On this page

Command Pattern

Most code performs an action the moment it decides to: document.insert(...), account.refund(...). Command separates those two moments. The decision becomes an object, and the object can be run now, later, on another thread, twice, or backwards. That one move unlocks undo and redo, macros, job queues, retries, audit logs and replay, which is why Command shows up in LLD rounds about text editors, chess, drawing tools, smart-home remotes and task schedulers. The behavioral patterns overview shows a short undo history and a CQRS command. This page builds a full editor history in Java, Python and TypeScript, then covers macros, queues, the three ways to implement undo, and how the chess case study uses commands for moves.

Intent

Wrap a request (the operation and everything it needs) in an object, so the code that triggers the request is separated from the code that performs it, and the request itself can be stored, passed around, queued, undone or replayed.

A command object answers three questions on its own: what to do (its class or type), to what (the receiver it holds a reference to, such as the document) and with what (its arguments: the position, the text). Anything that holds a command can run it without knowing any of those details. That's the decoupling. The fact that the command is a value you can keep is the superpower: once requests are objects, a list of them is a history, a queue or a script.

The problem

A small text editor wires its toolbar and keyboard shortcuts straight to the document. Undo was added later as an afterthought:

import java.util.*;

class Document {
    final StringBuilder text = new StringBuilder();
}

class EditorController {
    private final Document doc = new Document();
    private final Deque<String> undoLog = new ArrayDeque<>();   // "insert|pos|text" or "delete|pos|removed"

    void handle(String action, int pos, String arg) {
        switch (action) {
            case "insert" -> {
                doc.text.insert(pos, arg);
                undoLog.push("insert|" + pos + "|" + arg);
            }
            case "delete" -> {
                int len = Integer.parseInt(arg);
                String removed = doc.text.substring(pos, pos + len);
                doc.text.delete(pos, pos + len);
                undoLog.push("delete|" + pos + "|" + removed);
            }
            case "uppercase" -> {
                String upper = doc.text.toString().toUpperCase();
                doc.text.setLength(0);
                doc.text.append(upper);
                // TODO: undo for uppercase
            }
            default -> throw new IllegalArgumentException(action);
        }
    }

    void undo() {
        if (undoLog.isEmpty()) return;
        String[] parts = undoLog.pop().split("\\|", 3);   // breaks if the text contains "|"... or does it?
        int pos = Integer.parseInt(parts[1]);
        if (parts[0].equals("insert")) doc.text.delete(pos, pos + parts[2].length());
        else doc.text.insert(pos, parts[2]);
    }
    // redo: not supported
}

The trouble:

  • Every action is a branch in one method. Adding "replace all" means editing handle and undo, and remembering to keep them in sync.
  • The undo information is encoded in strings and decoded by a second switch. The format is a private protocol between two methods, and uppercase simply forgot to join in. Undoing after an uppercase now corrupts the document silently, because the positions in the log no longer match.
  • No redo, no grouping. "Find and replace 12 occurrences" can only be undone one occurrence at a time, if at all.
  • The UI is welded to the logic. The menu, the toolbar and the shortcut handler all have to call handle("insert", ...) with the right magic string. A macro recorder or a scripting API would need to do the same.
  • Nothing else can use the requests. You can't queue them, log them for crash recovery or send them to a collaborator's editor, because they don't exist as values. They're just method calls that happened.

Structure

classDiagram
    class Command {
        <<interface>>
        +execute()
        +undo()
        +label(): String
    }
    class InsertText {
        -doc: TextDocument
        -pos: int
        -text: String
        +execute()
        +undo()
    }
    class DeleteText {
        -doc: TextDocument
        -pos: int
        -len: int
        -removed: String
        +execute()
        +undo()
    }
    class Macro {
        -steps: List~Command~
        +execute()
        +undo()
    }
    class TextDocument {
        +insert(pos, text)
        +delete(pos, len): String
        +text(): String
    }
    class History {
        -undoStack: Deque~Command~
        -redoStack: Deque~Command~
        +run(command)
        +undo(): boolean
        +redo(): boolean
    }
    Command <|.. InsertText
    Command <|.. DeleteText
    Command <|.. Macro
    Macro o-- Command : steps
    InsertText --> TextDocument : receiver
    DeleteText --> TextDocument : receiver
    History o-- Command : "undo and redo stacks"

Participants

ParticipantIn this exampleResponsibilities
Command (interface)CommandDeclares execute and, when undo is needed, undo. Often also a label for menus and logs.
Concrete commandInsertText, DeleteTextBinds a receiver to an action and its arguments. Captures whatever it needs to reverse itself (DeleteText remembers the text it removed).
ReceiverTextDocumentThe object that actually knows how to do the work. Has no idea commands exist.
InvokerHistory (and, in a real editor, the menu and shortcut handlers)Triggers commands and decides when. Here it also keeps the undo and redo stacks.
Clientthe UI wiring, a script, a testCreates concrete commands with the right receiver and arguments, and hands them to the invoker.
Composite commandMacroA command made of commands. Runs them in order and undoes them in reverse.

Keep the receiver dumb about commands. TextDocument.insert and delete are ordinary methods. The commands are a layer on top that adds history, which means the document stays easy to test and reuse.

Implementation

The three versions share the same rules, and an interviewer will expect you to state them:

  1. run executes, then pushes onto the undo stack, then clears the redo stack. A new action after an undo makes the old "future" unreachable, which is how every mainstream editor behaves.
  2. Undo pops from the undo stack, reverses, and pushes onto redo. Redo is the mirror image.
  3. A command that fails during execute never enters the history. Otherwise undo would try to reverse something that never happened.
  4. A macro is atomic. If step 3 of 5 fails, steps 2 and 1 are undone before the error propagates, so the document is never left half-edited.
  5. History is bounded. Unlimited history is a memory leak with a nice name.
import java.util.*;

final class TextDocument {
    private final StringBuilder text = new StringBuilder();

    void insert(int pos, String s) {
        if (pos < 0 || pos > text.length()) throw new IndexOutOfBoundsException("pos " + pos);
        text.insert(pos, s);
    }

    String delete(int pos, int len) {
        if (pos < 0 || len < 0 || pos + len > text.length()) throw new IndexOutOfBoundsException("range " + pos + "+" + len);
        String removed = text.substring(pos, pos + len);
        text.delete(pos, pos + len);
        return removed;
    }

    String text() { return text.toString(); }
    int length() { return text.length(); }
}

interface Command {
    void execute();
    void undo();
    String label();
}

final class InsertText implements Command {
    private final TextDocument doc;
    private final int pos;
    private final String text;
    InsertText(TextDocument doc, int pos, String text) { this.doc = doc; this.pos = pos; this.text = text; }
    public void execute() { doc.insert(pos, text); }
    public void undo() { doc.delete(pos, text.length()); }
    public String label() { return "Insert \"" + text + "\""; }
}

final class DeleteText implements Command {
    private final TextDocument doc;
    private final int pos;
    private final int len;
    private String removed;                       // captured at execute time, needed by undo
    DeleteText(TextDocument doc, int pos, int len) { this.doc = doc; this.pos = pos; this.len = len; }
    public void execute() { removed = doc.delete(pos, len); }
    public void undo() { doc.insert(pos, removed); }
    public String label() { return "Delete " + len + " chars"; }
}

final class Macro implements Command {
    private final String label;
    private final List<Command> steps;
    Macro(String label, List<Command> steps) { this.label = label; this.steps = List.copyOf(steps); }

    public void execute() {
        int done = 0;
        try {
            for (Command step : steps) { step.execute(); done++; }
        } catch (RuntimeException e) {
            for (int i = done - 1; i >= 0; i--) steps.get(i).undo();   // roll back the steps that ran
            throw e;
        }
    }
    public void undo() {
        for (int i = steps.size() - 1; i >= 0; i--) steps.get(i).undo();
    }
    public String label() { return label; }
}

final class History {
    private final Deque<Command> undoStack = new ArrayDeque<>();
    private final Deque<Command> redoStack = new ArrayDeque<>();
    private final int limit;
    History(int limit) { this.limit = limit; }

    void run(Command c) {
        c.execute();                               // throws? then nothing is recorded
        undoStack.push(c);
        redoStack.clear();
        if (undoStack.size() > limit) undoStack.removeLast();   // drop the oldest
    }

    boolean undo() {
        Command c = undoStack.poll();
        if (c == null) return false;
        c.undo();
        redoStack.push(c);
        return true;
    }

    boolean redo() {
        Command c = redoStack.poll();
        if (c == null) return false;
        c.execute();
        undoStack.push(c);
        return true;
    }

    Optional<String> nextUndoLabel() { return Optional.ofNullable(undoStack.peek()).map(Command::label); }
}

class Demo {
    public static void main(String[] args) {
        TextDocument doc = new TextDocument();
        History history = new History(100);

        history.run(new InsertText(doc, 0, "Hello"));
        history.run(new InsertText(doc, 5, " world"));
        history.run(new DeleteText(doc, 0, 6));
        assert doc.text().equals("world");

        assert history.undo() && doc.text().equals("Hello world");
        assert history.undo() && doc.text().equals("Hello");
        assert history.redo() && doc.text().equals("Hello world");

        history.run(new InsertText(doc, 11, "!"));           // new action clears redo
        assert !history.redo();
        assert history.nextUndoLabel().orElseThrow().equals("Insert \"!\"");

        int end = doc.length();
        history.run(new Macro("Add signature", List.of(
                new InsertText(doc, end, "\n"),
                new InsertText(doc, end + 1, "-- Asha"))));
        assert doc.text().equals("Hello world!\n-- Asha");
        assert history.undo() && doc.text().equals("Hello world!");   // one undo for the whole macro

        Macro broken = new Macro("Broken", List.of(
                new InsertText(doc, 0, ">> "),
                new DeleteText(doc, 500, 1)));                    // out of range
        try {
            history.run(broken);
            assert false : "macro should fail";
        } catch (IndexOutOfBoundsException expected) { }
        assert doc.text().equals("Hello world!");                // rolled back, nothing half-applied
        assert history.nextUndoLabel().orElseThrow().equals("Insert \"!\"");   // and not recorded

        History tiny = new History(2);
        TextDocument d2 = new TextDocument();
        for (String s : List.of("a", "b", "c")) tiny.run(new InsertText(d2, d2.length(), s));
        assert tiny.undo() && tiny.undo() && !tiny.undo();       // only the last two are undoable
        assert d2.text().equals("a");
        System.out.println("command demo ok");
    }
}
from collections import deque
from typing import Protocol


class TextDocument:
    def __init__(self) -> None:
        self._text = ""

    def insert(self, pos: int, s: str) -> None:
        if not 0 <= pos <= len(self._text):
            raise IndexError(f"pos {pos}")
        self._text = self._text[:pos] + s + self._text[pos:]

    def delete(self, pos: int, length: int) -> str:
        if pos < 0 or length < 0 or pos + length > len(self._text):
            raise IndexError(f"range {pos}+{length}")
        removed = self._text[pos:pos + length]
        self._text = self._text[:pos] + self._text[pos + length:]
        return removed

    @property
    def text(self) -> str:
        return self._text


class Command(Protocol):
    label: str
    def execute(self) -> None: ...
    def undo(self) -> None: ...


class InsertText:
    def __init__(self, doc: TextDocument, pos: int, text: str) -> None:
        self._doc, self._pos, self._text = doc, pos, text
        self.label = f'Insert "{text}"'

    def execute(self) -> None:
        self._doc.insert(self._pos, self._text)

    def undo(self) -> None:
        self._doc.delete(self._pos, len(self._text))


class DeleteText:
    def __init__(self, doc: TextDocument, pos: int, length: int) -> None:
        self._doc, self._pos, self._length = doc, pos, length
        self._removed = ""
        self.label = f"Delete {length} chars"

    def execute(self) -> None:
        self._removed = self._doc.delete(self._pos, self._length)

    def undo(self) -> None:
        self._doc.insert(self._pos, self._removed)


class Macro:
    def __init__(self, label: str, steps: list[Command]) -> None:
        self.label = label
        self._steps = list(steps)

    def execute(self) -> None:
        done: list[Command] = []
        try:
            for step in self._steps:
                step.execute()
                done.append(step)
        except Exception:
            for step in reversed(done):
                step.undo()
            raise

    def undo(self) -> None:
        for step in reversed(self._steps):
            step.undo()


class History:
    def __init__(self, limit: int) -> None:
        self._undo: deque[Command] = deque(maxlen=limit)   # oldest falls off automatically
        self._redo: list[Command] = []

    def run(self, command: Command) -> None:
        command.execute()
        self._undo.append(command)
        self._redo.clear()

    def undo(self) -> bool:
        if not self._undo:
            return False
        command = self._undo.pop()
        command.undo()
        self._redo.append(command)
        return True

    def redo(self) -> bool:
        if not self._redo:
            return False
        command = self._redo.pop()
        command.execute()
        self._undo.append(command)
        return True

    def next_undo_label(self) -> str | None:
        return self._undo[-1].label if self._undo else None


if __name__ == "__main__":
    doc, history = TextDocument(), History(limit=100)

    history.run(InsertText(doc, 0, "Hello"))
    history.run(InsertText(doc, 5, " world"))
    history.run(DeleteText(doc, 0, 6))
    assert doc.text == "world"

    assert history.undo() and doc.text == "Hello world"
    assert history.undo() and doc.text == "Hello"
    assert history.redo() and doc.text == "Hello world"

    history.run(InsertText(doc, 11, "!"))
    assert not history.redo()
    assert history.next_undo_label() == 'Insert "!"'

    end = len(doc.text)
    history.run(Macro("Add signature", [InsertText(doc, end, "\n"), InsertText(doc, end + 1, "-- Asha")]))
    assert doc.text == "Hello world!\n-- Asha"
    assert history.undo() and doc.text == "Hello world!"

    try:
        history.run(Macro("Broken", [InsertText(doc, 0, ">> "), DeleteText(doc, 500, 1)]))
        raise AssertionError("macro should fail")
    except IndexError:
        pass
    assert doc.text == "Hello world!"
    assert history.next_undo_label() == 'Insert "!"'

    tiny, d2 = History(limit=2), TextDocument()
    for s in "abc":
        tiny.run(InsertText(d2, len(d2.text), s))
    assert tiny.undo() and tiny.undo() and not tiny.undo()
    assert d2.text == "a"
    print("command demo ok")
function assert(cond: boolean, msg = "assertion failed"): asserts cond {
  if (!cond) throw new Error(msg);
}

class TextDocument {
  private value = "";
  text(): string { return this.value; }

  insert(pos: number, s: string): void {
    if (pos < 0 || pos > this.value.length) throw new RangeError(`pos ${pos}`);
    this.value = this.value.slice(0, pos) + s + this.value.slice(pos);
  }

  delete(pos: number, len: number): string {
    if (pos < 0 || len < 0 || pos + len > this.value.length) throw new RangeError(`range ${pos}+${len}`);
    const removed = this.value.slice(pos, pos + len);
    this.value = this.value.slice(0, pos) + this.value.slice(pos + len);
    return removed;
  }
}

interface Command {
  readonly label: string;
  execute(): void;
  undo(): void;
}

class InsertText implements Command {
  readonly label: string;
  constructor(private readonly doc: TextDocument, private readonly pos: number, private readonly text: string) {
    this.label = `Insert "${text}"`;
  }
  execute(): void { this.doc.insert(this.pos, this.text); }
  undo(): void { this.doc.delete(this.pos, this.text.length); }
}

class DeleteText implements Command {
  readonly label: string;
  private removed = "";
  constructor(private readonly doc: TextDocument, private readonly pos: number, private readonly len: number) {
    this.label = `Delete ${len} chars`;
  }
  execute(): void { this.removed = this.doc.delete(this.pos, this.len); }
  undo(): void { this.doc.insert(this.pos, this.removed); }
}

class Macro implements Command {
  constructor(readonly label: string, private readonly steps: readonly Command[]) {}
  execute(): void {
    const done: Command[] = [];
    try {
      for (const step of this.steps) { step.execute(); done.push(step); }
    } catch (err) {
      for (const step of done.reverse()) step.undo();
      throw err;
    }
  }
  undo(): void { for (const step of [...this.steps].reverse()) step.undo(); }
}

class History {
  private readonly undoStack: Command[] = [];
  private readonly redoStack: Command[] = [];
  constructor(private readonly limit: number) {}

  run(command: Command): void {
    command.execute();
    this.undoStack.push(command);
    this.redoStack.length = 0;
    if (this.undoStack.length > this.limit) this.undoStack.shift();
  }

  undo(): boolean {
    const command = this.undoStack.pop();
    if (!command) return false;
    command.undo();
    this.redoStack.push(command);
    return true;
  }

  redo(): boolean {
    const command = this.redoStack.pop();
    if (!command) return false;
    command.execute();
    this.undoStack.push(command);
    return true;
  }

  get nextUndoLabel(): string | undefined { return this.undoStack.at(-1)?.label; }
}

const doc = new TextDocument();
const history = new History(100);

history.run(new InsertText(doc, 0, "Hello"));
history.run(new InsertText(doc, 5, " world"));
history.run(new DeleteText(doc, 0, 6));
assert(doc.text() === "world");

assert(history.undo() && doc.text() === "Hello world");
assert(history.undo() && doc.text() === "Hello");
assert(history.redo() && doc.text() === "Hello world");

history.run(new InsertText(doc, 11, "!"));
assert(!history.redo());
assert(history.nextUndoLabel === 'Insert "!"');

const end = doc.text().length;
history.run(new Macro("Add signature", [new InsertText(doc, end, "\n"), new InsertText(doc, end + 1, "-- Asha")]));
assert(doc.text() === "Hello world!\n-- Asha");
assert(history.undo() && doc.text() === "Hello world!");

let failed = false;
try {
  history.run(new Macro("Broken", [new InsertText(doc, 0, ">> "), new DeleteText(doc, 500, 1)]));
} catch { failed = true; }
assert(failed && doc.text() === "Hello world!");
assert(history.nextUndoLabel === 'Insert "!"');

const tiny = new History(2);
const d2 = new TextDocument();
for (const s of ["a", "b", "c"]) tiny.run(new InsertText(d2, d2.text().length, s));
assert(tiny.undo() && tiny.undo() && !tiny.undo());
assert(d2.text() === "a");
console.log("command demo ok");

Two subtleties hide in this code.

DeleteText is stateful. It doesn't know what it will delete until it runs, so it records the removed text during execute. That makes each command instance single-use: it represents one deletion that happened, not "delete" in general. Don't share command instances between history entries.

Undo depends on the document being in exactly the state the command left it. InsertText.undo deletes text.length() characters at pos. That's only correct if nothing else changed the document in between, which the stack discipline guarantees: you can only undo the most recent command. The moment something edits the document outside the history (a collaborator, an auto-formatter, the "uppercase" action that skipped the log in the "before" code), the recorded positions are wrong. Rule: once you adopt Command for undo, every mutation goes through a command.

Undo and redo in depth

Three ways to undo

The editor above uses inverse operations: every command knows how to reverse itself. That's not the only option, and choosing well is a good interview signal.

ApproachHow undo worksMemoryPitfallsGood fit
Inverse operationEach command implements undo() as the opposite actionSmall: just the arguments and what was removedEvery command must have a correct inverse. Some don't (uppercase loses the original case)Text editors, chess moves, drawing tools
Snapshot (Memento)Command saves the receiver's state before executing, and undo restores itLarge: a copy per step, unless snapshots are shared or diffedCopying big state is slow. Must snapshot everything that changesSmall receivers, operations with no clean inverse
ReplayUndo resets to the initial state and re-executes all commands except the lastTiny: just the command logUndo cost grows with history, so add periodic checkpointsDeterministic systems, event-sourced models, games with a move list

The middle row is the Memento pattern working alongside Command: the command decides when to save, the memento holds what was saved. "Uppercase the whole document" is the textbook case for it, because the original casing can't be computed from the result, so the command must remember the old text. The bottom row is how event sourcing rebuilds state, and why it needs snapshots.

Practical details

  • Coalescing. Typing "hello" should be one undo step, not five. Editors merge a new command into the top of the undo stack when it's the same kind, adjacent and recent: give Command an optional mergeWith(next) that returns true if it absorbed the next one.
  • Commands that can't be undone. Sending an email, charging a card or printing can't be taken back. Either keep them out of the undo history, or offer a compensating command ("issue refund"), which is a new forward action rather than a true undo. Be explicit about this; pretending an external side effect is undoable is a bug waiting to happen.
  • Saved-state marker. Editors show "unsaved changes" by remembering which command was on top of the undo stack when the file was last saved, not by diffing text.
  • Redo invalidation. Clearing redo on a new command is the simple, standard rule. Tools that keep the abandoned future (an undo tree) exist, but they're a product feature you should only build when asked.

Commands in the chess case study

In the chess case study, each move is a command for exactly this reason. A move's undo has to restore more than the piece's square: the captured piece (which has left the board), the castling rook, a promoted pawn, the "has this king moved?" flags and the en passant target square. A pair of squares can't carry that; a Move command object can, by recording the previous values when it executes. The game keeps undo and redo stacks of moves, and the move list doubles as the game record you can replay. It's a good example of the inverse-operation approach where the command stores just enough prior state (a tiny, targeted memento) to make its inverse exact.

Macros

A macro is a command whose job is to run other commands, which is a Composite. The Macro class above shows the two rules that make it trustworthy:

  • Undo runs in reverse order. Steps often depend on earlier steps' results (the second insert in "Add signature" assumes the first newline is there), so they must be unwound last-in, first-out.
  • Execution is all-or-nothing. If a step fails, the steps that already ran are undone before the error escapes. Without this, a failed "find and replace" leaves the document half-replaced and has nothing in the history to undo it with.

Macros also enable recording. While "record" is on, the invoker appends every command it runs to a list. Saving that list as a Macro gives you a replayable script. This works only when commands describe their intent in a replayable way: "insert at the cursor" replays sensibly on another document; "insert at position 412" usually doesn't. That's a design question to raise if an interviewer asks for macro recording.

Queues, workers and retries

Because a command is an object, it can be handed to something else to run later or elsewhere. A thread pool that accepts Runnable tasks is the simplest command queue. For work that must survive restarts or cross process boundaries, the command has to become data: a serialisable message with a type and fields, plus a registry of handlers that know how to execute each type. That split (command as data, handler as behaviour) is the form CQRS uses, as shown in the behavioral patterns overview.

Once commands travel through a queue, three concerns appear that in-memory undo never had: retries (a handler can fail transiently), duplicates (a retry or a redelivery can run the same command twice) and poison messages (a command that will never succeed must not block the queue forever). The sketch below handles all three with a worker thread, an idempotency key per command and a dead-letter list:

import json
import queue
import threading
from collections.abc import Callable
from dataclasses import asdict, dataclass


@dataclass(frozen=True)
class SendInvoice:            # a command as data: no behaviour, fully serialisable
    command_id: str
    order_id: str
    email: str


@dataclass(frozen=True)
class RefundPayment:
    command_id: str
    order_id: str
    amount_cents: int


Cmd = SendInvoice | RefundPayment
TYPES: dict[str, type[SendInvoice] | type[RefundPayment]] = {"SendInvoice": SendInvoice, "RefundPayment": RefundPayment}


def encode(cmd: Cmd) -> str:
    return json.dumps({"type": type(cmd).__name__, **asdict(cmd)})


def decode(raw: str) -> Cmd:
    data = json.loads(raw)
    return TYPES[data.pop("type")](**data)


class Worker:
    def __init__(self, handlers: dict[type, Callable[[Cmd], None]], max_attempts: int = 3) -> None:
        self._handlers = handlers
        self._max_attempts = max_attempts
        self._queue: queue.Queue[tuple[str, int] | None] = queue.Queue()
        self.done: set[str] = set()           # idempotency: command ids already handled
        self.dead_letters: list[str] = []
        self._thread = threading.Thread(target=self._loop, daemon=True)
        self._thread.start()

    def submit(self, cmd: Cmd) -> None:
        self._queue.put((encode(cmd), 1))     # only strings cross the queue

    def _loop(self) -> None:
        while (item := self._queue.get()) is not None:
            raw, attempt = item
            cmd = decode(raw)
            try:
                if cmd.command_id not in self.done:
                    self._handlers[type(cmd)](cmd)
                    self.done.add(cmd.command_id)
            except Exception:
                if attempt < self._max_attempts:
                    self._queue.put((raw, attempt + 1))   # retry later
                else:
                    self.dead_letters.append(raw)        # give up, keep it for inspection
            finally:
                self._queue.task_done()
        self._queue.task_done()

    def drain_and_stop(self) -> None:
        self._queue.join()
        self._queue.put(None)
        self._thread.join()


sent: list[str] = []
refunds: list[int] = []
flaky_calls = {"n": 0}


def send_invoice(cmd: Cmd) -> None:
    assert isinstance(cmd, SendInvoice)
    flaky_calls["n"] += 1
    if flaky_calls["n"] == 1:
        raise ConnectionError("smtp timeout")   # transient: succeeds on retry
    sent.append(cmd.email)


def refund(cmd: Cmd) -> None:
    assert isinstance(cmd, RefundPayment)
    if cmd.amount_cents <= 0:
        raise ValueError("bad amount")          # permanent: will dead-letter
    refunds.append(cmd.amount_cents)


worker = Worker({SendInvoice: send_invoice, RefundPayment: refund})
worker.submit(SendInvoice("c1", "A1", "asha@example.com"))
worker.submit(RefundPayment("c2", "A1", 2_500))
worker.submit(RefundPayment("c2", "A1", 2_500))      # duplicate delivery of the same command
worker.submit(RefundPayment("c3", "A2", -1))
worker.drain_and_stop()

assert sent == ["asha@example.com"]                   # retried once, delivered once
assert refunds == [2_500]                             # duplicate ignored
assert len(worker.dead_letters) == 1 and '"c3"' in worker.dead_letters[0]
print("command queue ok")

Things to notice:

  • Commands as data lose undo. A queued RefundPayment is a request, not a reversible in-memory action. Reversal, if it exists, is another command (a compensating "re-charge"), which is the idea behind sagas.
  • The idempotency key belongs to the command, generated by whoever created it, not by the worker. That's what lets the duplicate c2 be recognised. In production, the "done" set lives in the same store as the effect, so recording it and applying the effect are atomic. See idempotent consumers.
  • A real system backs off between retries and uses a durable broker instead of an in-memory queue. The shape stays the same.

Functions as commands

In languages with closures, a command with no undo is just a function: Runnable, Callable, a Python callable or a TypeScript () => void. executor.submit(() -> sendInvoice(orderId)) is the Command pattern with no extra classes. Prefer a function when you only need "run this later". Move to a class or a data record when you need any of these: undo, a label for a menu or log, serialisation to a queue or file, equality and deduplication, or inspection ("how many refund commands are pending?"). Closures are opaque. You can call them, but you can't look inside, persist them, or reverse them.

Real-world uses

  • java.lang.Runnable and java.util.concurrent.Callable submitted to an ExecutorService: commands queued for a pool of worker threads. ScheduledExecutorService runs them later or periodically.
  • Swing's javax.swing.Action, which extends ActionListener and adds a name, icon, tooltip and enabled state. One Action can back a menu item, a toolbar button and a key binding, and disabling it disables all three.
  • Swing's undo framework, javax.swing.undo: UndoableEdit (with undo, redo, canUndo, canRedo), UndoManager as the history, and CompoundEdit for grouping edits, which is a macro.
  • VS Code's command system. Extensions register commands by id with vscode.commands.registerCommand, and the same command can be bound to the command palette, menus and keybindings.
  • Python's concurrent.futures.Executor.submit and task queues such as Celery, where a task invocation is serialised and executed by a worker.
  • CQRS command handlers: PlaceOrder as a data object routed to one handler. See CQRS.
  • LLD case studies: the chess game uses move commands for undo and redo. The vending machine and elevator can model button presses as commands queued for a controller.

When NOT to use it

  • There's no undo, queueing, logging or deferral requirement. Wrapping cart.addItem(sku) in AddItemCommand just to call execute() immediately adds a class and an indirection for nothing. That's over-patterning.
  • The caller needs the result right now. Commands work best as fire-and-forget or "do this later". If every call site immediately reads a return value, a direct method call is clearer. Queries in particular are not commands.
  • The effect is irreversible and you only wanted Command for undo. You can't undo a sent SMS. Model a compensating action honestly, or don't offer undo.
  • The receiver's state is huge and changes are broad. Inverse operations become hard to write correctly, and snapshots get expensive. Persistent (immutable, structurally shared) data structures may be a better fit than a command history.
  • Mutations can bypass the history. If you can't route every change through commands, inverse-operation undo will corrupt state. Either close the bypass or use snapshot-based undo.
PatternHow it relatesThe difference
MementoCommon partner for undo.Command represents an action; a memento is a saved state. A command can hold a memento to undo operations that have no clean inverse.
StrategyBoth wrap behaviour in an object.A strategy is how the context does a step it was always going to do, and it's reused across calls. A command is what to do, with its arguments bound, and is often a one-off record of a single request.
CompositeMacros are composite commands.Composite is the structural idea of treating a group like a single item; a macro applies it to commands.
ObserverBoth are messages as objects.A command asks for something to happen and usually has one handler. An event announces that something happened and can have many observers, or none.
Chain of ResponsibilityCommands often flow through a handler chain.The chain decides who handles a request (validation, auth, logging middleware); the command is the request.
PrototypeUsed to copy commands."Repeat last action" can clone the top command from history with fresh state.
MediatorA command bus is a mediator.Dispatching a command to its handler by type is mediation; the command is the message.

The smell that suggests it

  • A switch on an action string or enum in a UI handler, a controller or a message loop.
  • The same operation triggered from several places (menu, toolbar, shortcut, API) with duplicated wiring or duplicated enable/disable logic.
  • An ad-hoc undo log of strings, tuples or "previous value" fields scattered across a class.
  • Requests that need to outlive the call: "retry this later", "run this at 2 a.m.", "do this after the user confirms", "replay these on the replica".
  • An audit requirement ("who did what, when") that's being implemented by sprinkling log lines through every mutating method.
  • "Do these five things, and if any fails, undo the others" written as nested try/catch blocks.

Interview questions

  1. "How do you implement undo and redo?" Two stacks of commands. run executes and pushes to undo, then clears redo. undo pops, calls undo() and pushes to redo; redo is the reverse. A command that throws during execute is never pushed. Bound the undo stack, and route every mutation through commands so recorded positions stay valid.
  2. "What does a command need to store to undo itself?" Its arguments, plus anything the action destroys or overwrites: the deleted text, the captured chess piece, the previous status or flags. If the inverse can't be computed, store a snapshot (a memento) of what's about to change.
  3. "How would you group several edits into one undo step?" A macro (composite) command that executes its steps in order, undoes them in reverse, and rolls back already-executed steps if one fails. For typing, coalesce consecutive small commands into one with a mergeWith method.
  4. "How is Command different from Strategy?" A strategy is a reusable algorithm the context calls as part of its own job, usually stateless and long-lived. A command is a specific request with its receiver and arguments bound, often stateful, created per action and stored, queued or undone.
  5. "You need to run commands on a worker. What changes?" They become serialisable data plus handlers looked up by type. You need retries with backoff, an idempotency key per command so duplicates are harmless, and a dead-letter path for commands that keep failing. In-memory undo no longer applies; reversals become compensating commands.
  6. "What happens if a command can't be undone?" Keep it out of the undo history (or clear the history after it, with the user's knowledge), or provide a compensating command such as a refund. Don't fake an undo for an external side effect.
  7. "How would you add macro recording to the editor?" While recording, the invoker appends each executed command to a list; stopping saves the list as a macro. Commands should capture intent in replayable terms (relative to the cursor or selection) rather than absolute positions, or replay will misfire on a different document.
  8. "Why is a chess move a command and not just two squares?" Because undoing it needs everything the move changed: the captured piece, castling rook movement, promotion, castling-rights flags and the en passant square. The command records those as it executes, so undo restores the exact prior position, and the move list doubles as a replayable game record.
  9. "Is a closure a command?" Yes, for the "run this later" part: Runnable or () => void is a command without undo. Use a class or data record once you need undo, labels, serialisation, deduplication or inspection.

Further reading