Encapsulate a request as an object, so you can pass requests around as values, delay or queue their execution, record them, retry them and support undoable operations, all without the sender knowing how the work is carried out.
Command wraps a request in an object that knows what to do, to whom, and with which arguments. Once a request is an object, you can do things with it that a plain method call does not allow. You can store it, queue it, write it to an audit log, run it again after a failure, or reverse it. In interviews, Command comes up whenever a design needs undo, job queues, retries, macros or an audit trail. This guide follows one system from start to finish: the stock scanner app for a chain of bike shops. You will see why direct calls fall apart there, how commands fix it, and how to code it in TypeScript, Python and PHP.
The problem
A situation where the obvious design starts to hurt.
Spokehouse runs 38 bike shops. Staff record about 2,000 stock movements a day on handheld scanners: receiving deliveries, moving helmets from the Leeds shop to York, writing off damaged inner tubes. The first scanner app called the inventory service straight from each button handler: onTransferPressed called inventory.remove(...) and then inventory.add(...).
That design ran into four problems in its first month.
Back rooms have patchy Wi-Fi. When a call failed, the scan was lost, and staff had to remember to repeat it.
Ordering mattered. A transfer out of Leeds sometimes reached the server before the delivery that put the stock there, so it was rejected, even though it would have been valid a minute later.
The finance team wanted an audit trail of every movement, but the code that changes stock was spread across a dozen button handlers, each logging in its own way or not at all.
Staff mis-scan. A shop assistant who transfers 40 helmets instead of 4 needs a single undo button, and nothing in the code knew how to reverse an arbitrary operation.
Adding queueing, logging, retry and undo to every handler would mean duplicating the same plumbing a dozen times and coupling the UI to inventory internals.
The solution
What the pattern proposes.
Turn each stock movement into an object. ReceiveStock and TransferStock each implement a small StockCommand interface: execute(), undo() and describe(). The object holds everything it needs: a reference to the Inventory (the receiver), the store codes, the SKU and the quantity.
The scanner app no longer touches the inventory. It builds a command and submits it to a CommandRunner, the invoker. The runner owns the cross-cutting behaviour exactly once:
It keeps a queue of pending commands and executes them when flush() is called, for example when the connection comes back.
It writes one log line per lifecycle event, using describe(), which gives finance its audit trail.
If a command fails, it stays in the queue and is retried on the next flush, up to a maximum number of attempts. The transfer that arrived before the delivery simply succeeds on the second pass.
Every successful command goes onto a history stack, so undoLast() pops the latest one and calls its undo().
Adding a new movement type, such as WriteOffDamaged, means writing one new command class. The runner and the UI stay untouched.
An everyday analogy
The same idea, outside software.
Think of a dry cleaner's ticket. You hand over a jacket and get a ticket stating what to do (press, remove a stain), for whom, and by when. The ticket is the request turned into a thing. The shop can pile tickets in a tray and work through them later, file the stubs as a record of the day, put a ticket back in the tray if the stain did not come out first time, and use it to reverse the job if you come back saying it was the wrong jacket. Nobody at the counter needs to know how the machines work; they only handle tickets.
Structure
The pieces and how they relate.
Participants
- Command (StockCommand)
- Declares the operations every request supports:
execute()to perform it,undo()to reverse it, anddescribe()for logging. - Concrete commands (ReceiveStock, TransferStock)
- Store the receiver and all parameters of one specific request, and translate
execute()andundo()into calls on the receiver. - Receiver (Inventory)
- Holds the real business logic and state. It knows nothing about commands, queues or undo.
- Invoker (CommandRunner)
- Triggers commands without knowing what they do. Here it also owns the queue, the audit log, the retry policy and the undo history.
- Client (ScannerApp)
- Creates concrete commands with the right receiver and arguments, and hands them to the invoker.
Pseudocode
The solution to the scenario, language-neutral.
interface StockCommand
method execute()
method undo()
method describe(): string
class TransferStock implements StockCommand
fields inventory, from, to, sku, qty
method execute()
inventory.remove(from, sku, qty)
inventory.add(to, sku, qty)
method undo()
inventory.remove(to, sku, qty)
inventory.add(from, sku, qty)
class CommandRunner
fields pending = [], history = [], log = [], maxAttempts
method submit(command)
pending.append({command, attempts: 0})
log("queued: " + command.describe())
method flush()
batch = pending; pending = []
for entry in batch
entry.attempts += 1
try
entry.command.execute()
history.push(entry.command)
log("done: ...")
catch error
if entry.attempts < maxAttempts
pending.append(entry)
log("retry ...")
else
log("gave up: ...")
method undoLast()
command = history.pop()
if command exists
command.undo()
log("undone: ...")
// client
runner.submit(new TransferStock(inv, "leeds", "york", "HELMET-M", 4))
runner.submit(new ReceiveStock(inv, "leeds", "HELMET-M", 10))
runner.flush() // transfer fails, receive succeeds
runner.flush() // transfer retried and succeeds
runner.undoLast() // transfer reversedThe code
The same solution in TypeScript, Python and PHP.
class Inventory {
private stock = new Map<string, number>();
count(store: string, sku: string): number {
return this.stock.get(`${store}:${sku}`) ?? 0;
}
add(store: string, sku: string, qty: number): void {
this.stock.set(`${store}:${sku}`, this.count(store, sku) + qty);
}
remove(store: string, sku: string, qty: number): void {
const current = this.count(store, sku);
if (current < qty) {
throw new Error(`only ${current} of ${sku} at ${store}`);
}
this.stock.set(`${store}:${sku}`, current - qty);
}
}
interface StockCommand {
execute(): void;
undo(): void;
describe(): string;
}
class ReceiveStock implements StockCommand {
constructor(
private inventory: Inventory,
private store: string,
private sku: string,
private qty: number,
) {}
execute(): void {
this.inventory.add(this.store, this.sku, this.qty);
}
undo(): void {
this.inventory.remove(this.store, this.sku, this.qty);
}
describe(): string {
return `receive ${this.qty} ${this.sku} at ${this.store}`;
}
}
class TransferStock implements StockCommand {
constructor(
private inventory: Inventory,
private from: string,
private to: string,
private sku: string,
private qty: number,
) {}
execute(): void {
this.inventory.remove(this.from, this.sku, this.qty);
this.inventory.add(this.to, this.sku, this.qty);
}
undo(): void {
this.inventory.remove(this.to, this.sku, this.qty);
this.inventory.add(this.from, this.sku, this.qty);
}
describe(): string {
return `transfer ${this.qty} ${this.sku} ${this.from} -> ${this.to}`;
}
}
interface PendingEntry {
command: StockCommand;
attempts: number;
}
class CommandRunner {
private pending: PendingEntry[] = [];
private history: StockCommand[] = [];
readonly log: string[] = [];
constructor(private maxAttempts = 3) {}
submit(command: StockCommand): void {
this.pending.push({ command, attempts: 0 });
this.log.push(`queued: ${command.describe()}`);
}
flush(): void {
const batch = this.pending;
this.pending = [];
for (const entry of batch) {
entry.attempts += 1;
const description = entry.command.describe();
try {
entry.command.execute();
this.history.push(entry.command);
this.log.push(`done: ${description}`);
} catch (error) {
const reason = error instanceof Error ? error.message : String(error);
if (entry.attempts < this.maxAttempts) {
this.pending.push(entry);
this.log.push(`retry ${entry.attempts}/${this.maxAttempts}: ${description} (${reason})`);
} else {
this.log.push(`gave up: ${description} (${reason})`);
}
}
}
}
undoLast(): void {
const command = this.history.pop();
if (!command) return;
command.undo();
this.log.push(`undone: ${command.describe()}`);
}
}
const inventory = new Inventory();
const runner = new CommandRunner(3);
runner.submit(new TransferStock(inventory, "leeds", "york", "HELMET-M", 4));
runner.submit(new ReceiveStock(inventory, "leeds", "HELMET-M", 10));
runner.flush(); // transfer fails, delivery is recorded
runner.flush(); // transfer retried and succeeds
runner.undoLast(); // staff reverse the transfer
console.log(runner.log.join("\n"));
console.log(inventory.count("leeds", "HELMET-M"), inventory.count("york", "HELMET-M")); // 10 0from abc import ABC, abstractmethod
from dataclasses import dataclass
class Inventory:
def __init__(self) -> None:
self._stock: dict[str, int] = {}
def count(self, store: str, sku: str) -> int:
return self._stock.get(f"{store}:{sku}", 0)
def add(self, store: str, sku: str, qty: int) -> None:
self._stock[f"{store}:{sku}"] = self.count(store, sku) + qty
def remove(self, store: str, sku: str, qty: int) -> None:
current = self.count(store, sku)
if current < qty:
raise ValueError(f"only {current} of {sku} at {store}")
self._stock[f"{store}:{sku}"] = current - qty
class StockCommand(ABC):
@abstractmethod
def execute(self) -> None: ...
@abstractmethod
def undo(self) -> None: ...
@abstractmethod
def describe(self) -> str: ...
class ReceiveStock(StockCommand):
def __init__(self, inventory: Inventory, store: str, sku: str, qty: int) -> None:
self._inventory = inventory
self._store = store
self._sku = sku
self._qty = qty
def execute(self) -> None:
self._inventory.add(self._store, self._sku, self._qty)
def undo(self) -> None:
self._inventory.remove(self._store, self._sku, self._qty)
def describe(self) -> str:
return f"receive {self._qty} {self._sku} at {self._store}"
class TransferStock(StockCommand):
def __init__(self, inventory: Inventory, source: str, target: str, sku: str, qty: int) -> None:
self._inventory = inventory
self._source = source
self._target = target
self._sku = sku
self._qty = qty
def execute(self) -> None:
self._inventory.remove(self._source, self._sku, self._qty)
self._inventory.add(self._target, self._sku, self._qty)
def undo(self) -> None:
self._inventory.remove(self._target, self._sku, self._qty)
self._inventory.add(self._source, self._sku, self._qty)
def describe(self) -> str:
return f"transfer {self._qty} {self._sku} {self._source} -> {self._target}"
@dataclass
class PendingEntry:
command: StockCommand
attempts: int = 0
class CommandRunner:
def __init__(self, max_attempts: int = 3) -> None:
self._max_attempts = max_attempts
self._pending: list[PendingEntry] = []
self._history: list[StockCommand] = []
self.log: list[str] = []
def submit(self, command: StockCommand) -> None:
self._pending.append(PendingEntry(command))
self.log.append(f"queued: {command.describe()}")
def flush(self) -> None:
batch, self._pending = self._pending, []
for entry in batch:
entry.attempts += 1
description = entry.command.describe()
try:
entry.command.execute()
except ValueError as error:
if entry.attempts < self._max_attempts:
self._pending.append(entry)
self.log.append(
f"retry {entry.attempts}/{self._max_attempts}: {description} ({error})"
)
else:
self.log.append(f"gave up: {description} ({error})")
else:
self._history.append(entry.command)
self.log.append(f"done: {description}")
def undo_last(self) -> None:
if not self._history:
return
command = self._history.pop()
command.undo()
self.log.append(f"undone: {command.describe()}")
inventory = Inventory()
runner = CommandRunner(3)
runner.submit(TransferStock(inventory, "leeds", "york", "HELMET-M", 4))
runner.submit(ReceiveStock(inventory, "leeds", "HELMET-M", 10))
runner.flush() # transfer fails, delivery is recorded
runner.flush() # transfer retried and succeeds
runner.undo_last() # staff reverse the transfer
print("\n".join(runner.log))
print(inventory.count("leeds", "HELMET-M"), inventory.count("york", "HELMET-M")) # 10 0<?php
declare(strict_types=1);
final class Inventory
{
/** @var array<string, int> */
private array $stock = [];
public function count(string $store, string $sku): int
{
return $this->stock["{$store}:{$sku}"] ?? 0;
}
public function add(string $store, string $sku, int $qty): void
{
$this->stock["{$store}:{$sku}"] = $this->count($store, $sku) + $qty;
}
public function remove(string $store, string $sku, int $qty): void
{
$current = $this->count($store, $sku);
if ($current < $qty) {
throw new RuntimeException("only {$current} of {$sku} at {$store}");
}
$this->stock["{$store}:{$sku}"] = $current - $qty;
}
}
interface StockCommand
{
public function execute(): void;
public function undo(): void;
public function describe(): string;
}
final class ReceiveStock implements StockCommand
{
public function __construct(
private Inventory $inventory,
private string $store,
private string $sku,
private int $qty,
) {}
public function execute(): void
{
$this->inventory->add($this->store, $this->sku, $this->qty);
}
public function undo(): void
{
$this->inventory->remove($this->store, $this->sku, $this->qty);
}
public function describe(): string
{
return "receive {$this->qty} {$this->sku} at {$this->store}";
}
}
final class TransferStock implements StockCommand
{
public function __construct(
private Inventory $inventory,
private string $from,
private string $to,
private string $sku,
private int $qty,
) {}
public function execute(): void
{
$this->inventory->remove($this->from, $this->sku, $this->qty);
$this->inventory->add($this->to, $this->sku, $this->qty);
}
public function undo(): void
{
$this->inventory->remove($this->to, $this->sku, $this->qty);
$this->inventory->add($this->from, $this->sku, $this->qty);
}
public function describe(): string
{
return "transfer {$this->qty} {$this->sku} {$this->from} -> {$this->to}";
}
}
final class PendingEntry
{
public int $attempts = 0;
public function __construct(public readonly StockCommand $command) {}
}
final class CommandRunner
{
/** @var PendingEntry[] */
private array $pending = [];
/** @var StockCommand[] */
private array $history = [];
/** @var string[] */
public array $log = [];
public function __construct(private int $maxAttempts = 3) {}
public function submit(StockCommand $command): void
{
$this->pending[] = new PendingEntry($command);
$this->log[] = 'queued: ' . $command->describe();
}
public function flush(): void
{
$batch = $this->pending;
$this->pending = [];
foreach ($batch as $entry) {
$entry->attempts++;
$description = $entry->command->describe();
try {
$entry->command->execute();
$this->history[] = $entry->command;
$this->log[] = "done: {$description}";
} catch (RuntimeException $error) {
$reason = $error->getMessage();
if ($entry->attempts < $this->maxAttempts) {
$this->pending[] = $entry;
$this->log[] = "retry {$entry->attempts}/{$this->maxAttempts}: {$description} ({$reason})";
} else {
$this->log[] = "gave up: {$description} ({$reason})";
}
}
}
}
public function undoLast(): void
{
$command = array_pop($this->history);
if ($command === null) {
return;
}
$command->undo();
$this->log[] = 'undone: ' . $command->describe();
}
}
$inventory = new Inventory();
$runner = new CommandRunner(3);
$runner->submit(new TransferStock($inventory, 'leeds', 'york', 'HELMET-M', 4));
$runner->submit(new ReceiveStock($inventory, 'leeds', 'HELMET-M', 10));
$runner->flush(); // transfer fails, delivery is recorded
$runner->flush(); // transfer retried and succeeds
$runner->undoLast(); // staff reverse the transfer
echo implode("\n", $runner->log), "\n";
echo $inventory->count('leeds', 'HELMET-M'), ' ', $inventory->count('york', 'HELMET-M'), "\n"; // 10 0When to use it
Situations where it pays off.
You need undo or redo for operations that change state.
A command carries the exact parameters it ran with, so it can reverse itself. A history stack of commands gives you multi-level undo without the receiver tracking anything.
Requests must be delayed, queued or run somewhere else, such as on reconnect or on a worker.
A command is a value you can hold onto. The sender builds it now; the invoker executes it later, on its own schedule.
You need an audit trail or the ability to replay operations.
Every request passes through one invoker as a self-describing object, so logging lives in one place, and serialisable commands can be replayed to rebuild state.
Failed operations should be retried without the caller resubmitting them.
The invoker keeps the failed command and runs it again. The caller does not need to remember the original arguments.
UI elements, schedulers or scripts should trigger operations without depending on business classes.
The trigger only depends on the command interface, so the same button, hotkey or cron job can run any command.
How to implement it
Steps to introduce it in existing code.
Pick the operations that need queueing, logging, retry or undo, and identify the receiver that does the real work for each one.
Declare a command interface with
execute(), plusundo()if you need reversal and adescribe()or serialisation method if you need logging or persistence.Write one concrete command class per operation. Pass the receiver and every argument through the constructor and store them, so the command is self-contained.
Implement
undo()as the exact inverse ofexecute(). If the inverse cannot be computed from the arguments alone, capture the old state insideexecute()before changing it.Build an invoker that accepts commands and owns the policies: a pending queue, a retry counter per command, a log, and a history stack of successful commands.
Change the clients so they create commands and pass them to the invoker instead of calling the receiver directly.
Decide what happens to the history when a new command runs after an undo (usually clear the redo stack) and cap the history size so it does not grow without bound.
Pros and cons
What you gain and what you pay.
Pros
- Queueing, logging, retry and undo are implemented once in the invoker instead of in every caller.
- Senders are decoupled from receivers: the scanner app does not know how inventory works.
- New operations are new classes, so existing code stays closed to modification.
- Commands are values, so you can store, serialise, schedule, replay or batch them into macros.
- Each command is small and easy to unit test in isolation from the UI.
Cons
- Every operation gets its own class, which adds files and indirection for simple actions.
- Correct undo is hard when operations have side effects outside your system, such as emails or payments; you may need compensating actions instead.
- Retrying commands is only safe if they are idempotent or the receiver can detect duplicates.
- Commands that hold live references to receivers cannot be serialised directly; persisting them needs IDs and a way to rebuild the receiver on load.
Relations with other guides
Patterns it's often confused or combined with.
- Memento Pattern: Save and Restore State Without Exposing It
When a command cannot compute its own inverse, it can take a Memento of the receiver before executing and restore it on undo.
- Composite Pattern: Treat Single Items and Groups Through One Interface
A macro command is a Composite: it holds a list of commands and executes them in order, undoing them in reverse.
- Strategy: swap the rule without touching who uses it
Both wrap behaviour in an object. Strategy swaps how one job is done; Command captures what to do so it can be queued, logged or undone.
- Chain of Responsibility: Pass a Request Along Until One Handles It
Handlers in a chain often pass a command object along, so each handler can inspect, enrich or execute the same request.
- Idempotency Keys: Making Retried Writes Safe
Retrying commands across a network is only safe if each command carries an idempotency key the receiver can use to drop duplicates.
- Replace Function with Command: Turn a Long Function into an Object
This refactoring is the code-level move that introduces a command: turn a long function into an object with an execute method.
Common questions
Short answers to the usual doubts.
What is the difference between the invoker and the receiver?
The receiver does the real work: Inventory knows how to add and remove stock. The invoker decides when and how often commands run: CommandRunner queues, retries, logs and undoes them without knowing what any command does. The command sits between them and is the only piece that knows both.
How do you implement redo?
Keep a second stack. When undoLast() reverses a command, push it onto the redo stack; redoLast() pops it, calls execute() again and pushes it back onto history. Clear the redo stack whenever a brand-new command executes, because the old future no longer applies.
What if an operation cannot be reversed from its arguments alone?
Capture the previous state inside execute() before changing anything, for example the old price before a price change, and store it on the command. For larger state, take a Memento of the receiver. For external side effects such as a sent email, undo means issuing a compensating action, not erasing history.
Is it safe to retry any command?
No. A retry is only safe if running the command twice has the same effect as running it once, or the receiver can recognise a duplicate. Over a network, the first attempt may have succeeded even though the caller saw a failure, so give each command a unique ID and let the receiver ignore IDs it has already applied.
How is Command different from just passing a callback?
A callback is a minimal command with only execute. In languages with closures that is often enough for deferred execution. You need a full command object when you also want undo, a human-readable description for logs, serialisation for a persistent queue, or retry metadata such as attempt counts.
What do interviewers usually want to hear about Command?
That it decouples who requests an operation from who performs it, that the request becomes a value you can queue, log, retry and undo, and that the trade-off is more classes plus the work of making undo and retries correct. Mention idempotency for retries and history size limits for undo to show you have thought past the diagram.