Pattern 09/22 · Behavioral

Command

Wrap a "thing to do" (its parameters, the object it acts on, how to do it, how to undo it) in an object, so you can queue it, log it, send it somewhere, retry it, replay it or undo it — instead of calling a function and losing all trace of it.

Behavioral●●○14 min read8 stepsalso known as: Action, Task, Transaction
undo redoqueueretryevent sourcingbehavioralmacroserializable

01 — It starts with code that is breaking

Problem

You build a small editor. insert(at, text) and remove(at, n) mutate the text string directly, and the "Send" button calls api.send(text). Everything works until someone says three little words: "needs undo support".

Everyone writes the first version the same way: const last = text before editing, and undo does text = last. It works. Then comes "undo twice", then "redo", then "the undo button tooltip has to show the name of the action it will revert". last becomes history: string[] — a full copy of the text after every keystroke. Memory grows, and more importantly: your history only contains snapshots, not what was done, so it can't show an action name, can't merge 40 keystrokes into one undo, and can't explain anything to an audit log.

Meanwhile, three more requirements land. The "Send" button must retry three times on a flaky network. When offline, the user can still click it, and the work runs once the connection is back. Admins must be able to see "who changed this order to cancelled, and when". And a 40-file refactor has to be undone as a whole, not with 40 presses of Ctrl+Z.

You could write four separate mechanisms: an array of snapshots, a retry loop, a localStorage queue, an audit table. Those four will drift apart by next week, because each one invents its own way of describing "what just happened".

Those four requirements are one requirement: an action has to be an object that outlives the function call. Once it is an object, you can queue it, log it, send it over the network, undo it — and all four features get written once, for every kind of action.

02 — The idea, before touching code

Solution

Command means: instead of doThing(args), you build an object describing that work, and only then run it. The object carries the parameters, points to the object being acted on, knows how to execute() and — if it can be reverted — how to undo(). Whoever creates the command and whoever runs it are no longer the same.

The rest of the system only talks to that contract. The Invoker (a button, a queue, a cron job, a worker) calls execute() whenever it wants, and knows nothing about the editor or the DB. Want "wait 5 seconds then run", "retry 3 times on error", "log it"? You change the invoker — every command gets it for free, and none of them has to change.

In TS, a command is usually an object { label, execute(), undo() }, or plain data { type, payload } like a Redux action. The latter matters more than it looks: if it serialises, you can send it to a worker, store it in a DB, replay it to rebuild state. Redux dispatch(action), job queues (BullMQ), queueMicrotask, ProseMirror/Slate history — they all share this shape.

03 — Doing it for real, one code fragment per step

Step by step

1

Write the "call it and forget it" version first

This is the code everyone writes. It isn't wrong — it just leaves no trace. Once insert() finishes, nobody knows what just happened, who caused it, or how to reverse it.

tseditor-v1.ts
let text = ''
let last = ''                       // one-step "undo"

function insert(at: number, s: string) {
  last = text                       // snapshot the whole text
  text = text.slice(0, at) + s + text.slice(at)
}

function undo() { text = last }

insert(0, 'hey')
insert(3, ' there')
undo()                              // back to "hey"
undo()                              // still "hey" <- only one undo step
Snapshotting the whole state: memory-hungry, no names, no redo, no grouping, no log.
Key pointIf your history stores state instead of actions, you lose the ability to explain, group and undo things in a meaningful way.
2

The Command contract: execute, plus undo if it can be reverted

One interface, two methods. label isn't mechanically required, but it's what turns history into something humans can read — the undo button tooltip, the audit log, devtools. Treat it as required.

Note that undo() is optional (undo?()): some things can't be reversed by logic — sending an email, charging a card, calling a webhook. Pretending everything is undoable is the source of bugs like "undo succeeded but the money is still gone", so be honest in the type: undo is an optional method.

tscommand.ts
export interface Command {
  /** Human readable: 'insert "there" @3', 'status o-1 -> cancelled' */
  readonly label: string
  execute(): void
  /** Leave it out if this can't be reverted (email sent, card charged). */
  undo?(): void
}
Key pointCommand separates "what to do" from "when to do it and who does it". That is the whole reason it exists.
3

Turn each operation into a command: parameters frozen at creation

Each operation becomes a factory that returns a command. The key point: the command holds a diff (at position 3, insert " there"), not a snapshot of the whole state. It's cheap, and it describes the intent precisely.

before is read when the command is built, which is when the parameters freeze. For a single-user editor that's correct. Once co-editing or autosave sneaks in between, the "old state" you captured at creation time may be stale — then you have to snapshot inside execute(), or move to transforms/OT/CRDT. Knowing this limit up front saves you a night on call.

tsinsert-command.ts
const doc = { text: '' }

export const insert = (at: number, s: string): Command => ({
  label: 'insert "' + s + '" @' + at,
  execute: () => { doc.text = doc.text.slice(0, at) + s + doc.text.slice(at) },
  undo: () => { doc.text = doc.text.slice(0, at) + doc.text.slice(at + s.length) },
})

export const remove = (at: number, n: number): Command => {
  const removed = doc.text.slice(at, at + n)   // remember the content BEFORE deleting
  return {
    label: 'remove "' + removed + '" @' + at,
    execute: () => { doc.text = doc.text.slice(0, at) + doc.text.slice(at + n) },
    undo: () => { doc.text = doc.text.slice(0, at) + removed + doc.text.slice(at) },
  }
}
Key pointA command stores its own inverse, not the whole world. That's why an editor's history doesn't eat your RAM.
4

The invoker: history + a cursor, and the "new command kills redo" rule

Undo/redo is one array with a cursor, not two arrays. run pushes the command and moves the cursor forward; undo moves the cursor back and calls undo(); redo moves the cursor forward and calls execute(). Please don't write two separate stacks — that's where "redo lost my command" bugs are born.

There is exactly one rule to remember: when the user runs a new command in the middle of history, everything after the cursor dies. You undo three steps and keep typing — those three redoable steps no longer exist. Write the one-liner history.splice(cursor), and explain it to product today so you don't have to argue about it next week.

tshistory.ts
const history: Command[] = []
let cursor = 0

export function run(cmd: Command) {
  cmd.execute()
  history.splice(cursor)   // a new command kills everything after the cursor
  history.push(cmd)
  cursor++
}

export function undo() {
  if (cursor === 0) return
  const cmd = history[--cursor]
  cmd.undo?.()
}

export function redo() {
  if (cursor === history.length) return
  const cmd = history[cursor++]
  cmd.execute()
}
Key pointThe invoker knows nothing about the editor. It only knows "this object has execute() and maybe undo()" — so it works for every kind of command.
5

Try it: undo a macro, redo, and watch redo get killed

The lines below cover the full lifecycle: run two commands, run a macro of several keystrokes that a single undo reverts back to exactly where it was, redo, then a new command wipes out the redo branch.

tsmain.ts
run(insert(0, 'hey'))
run(insert(3, ' there'))
run(macro('rename variable', [insert(9, ' pal'), insert(13, '!')]))
undo(); undo(); redo()
run(insert(0, '>> '))
redo()
console
run   insert "hey" @0      | hey
run   insert " there" @3   | hey there
run   rename variable      | hey there pal!
undo  rename variable      | hey there
undo  insert " there" @3   | hey
redo  insert " there" @3   | hey there
run   insert ">> " @0      | >> hey there
redo  (nothing left)       | >> hey there
6

Macro: a composite command, undone as one

Because a macro is also a Command, the invoker can't tell it apart from an atomic one. Pasting 400 characters, a bulk rename, "move 5 orders to cancelled" — each becomes one undo step. This is something snapshot-based history never gets right, because a snapshot doesn't know those 40 changes belong to one action.

Just remember: undo has to run in reverse order, and the macro's undo() must count as a single action — if the invoker logs each child command, your audit log will lie.

tsmacro.ts
export const macro = (label: string, cmds: Command[]): Command => ({
  label,
  execute: () => cmds.forEach(c => c.execute()),
  undo: () => [...cmds].reverse().forEach(c => c.undo?.()),
})

// Composite: Command is one, Command[] is many, same contract.
// Same contract means macros nest inside macros, and the invoker doesn't change a line.
Key pointOne contract for "one" and "many" — Command wearing Composite's clothes, and that's how pasting 400 characters undoes in one go.
7

Commands as data: if it serialises, you can queue, retry and replay it

Drop the two closures and keep the description: { type, at, text }. Now the command is JSON: write it to a DB, send it to a worker via postMessage, push it into BullMQ, stash it in localStorage while offline. A single apply(doc, cmd) function runs it, and invert(cmd) produces the reverse command. History becomes data — you can time-travel, replay, diff, and stream it to another device.

This is exactly Redux: an action is a data command, dispatch is the invoker, the reducer is the receiver; DevTools can time-travel because actions are plain objects. It's also the foundation of event sourcing: state = a fold over the list of commands, so you can rebuild state at any point without storing snapshots.

The cost: apply and invert become an API contract. Adding a field is a breaking change for commands already stored in the DB. Design the shape once, and version it.

tsdata-command.ts
type Cmd = { type: 'insert', at: number, text: string }
        | { type: 'remove', at: number, text: string }

export const apply = (doc: { text: string }, c: Cmd): void => {
  if (c.type === 'insert') doc.text = doc.text.slice(0, c.at) + c.text + doc.text.slice(c.at)
  else doc.text = doc.text.slice(0, c.at) + doc.text.slice(c.at + c.text.length)
}

/** The inverse command is data too -> undo still works after a reload. */
export const invert = (c: Cmd): Cmd =>
  c.type === 'insert'
    ? { type: 'remove', at: c.at, text: c.text }
    : { type: 'insert', at: c.at, text: c.text }

// JSON.stringify(cmd) -> queue / worker / offline queue / event store
Key pointCommands with closures run fast; commands as data survive a restart and travel over the network. Choose by how long the command needs to live.
8

A production invoker: retry, offline, and commands you can't undo

This is where Command pays for itself. Everything below lives in the invoker: every command gets retry, backoff, a history cap and an audit log without any command rewriting those lines. Adding "run when back online" = 5 more lines in the invoker, not 40 scattered patches.

But be honest about undo. A command that sent an email, charged a card, or called a partner's webhooks has no inverse. Don't invent an undo() just to satisfy the interface; use compensation (a new command that neutralises the effect) and leave undo empty. An undo() that pretends to "run backwards" is a bug designed in advance.

tsinvoker.ts
const MAX_HISTORY = 100   // history is RAM, it needs a ceiling

export async function runWithRetry(cmd: Command, attempts = 3): Promise<boolean> {
  for (let i = 1; i <= attempts; i++) {
    try {
      cmd.execute()
      history.push(cmd)
      if (history.length > MAX_HISTORY) history.shift()
      return true
    }
    catch (e) {
      if (i === attempts) return false   // log cmd.label, do NOT log cmd.undo
    }
  }
  return false
}
Key pointBefore turning something into a Command, ask: does this action need to outlive the function call? If not, a function is enough, and it's cheaper.

04 — Who talks to whom

Structure

  • CommandThe contract: `label` + `execute()`, plus `undo()` if it can be reverted. Knows nothing about the UI, the DB, or other commands.
  • ConcreteCommand`insert`, `remove`, `updateStatus`, `macro`. Holds the parameters frozen at creation and points to the receiver.
  • ReceiverThe thing actually being changed: `doc.text`, a DB row, a list of orders. Doesn't know which button the command came from.
  • InvokerButton, queue, cron, worker, DevTools. Chooses **when** to run, handles retry/offline/history. Does not choose **how**.
  • History / CaretAn array of commands + a cursor. Decides what undo/redo still has, and kills the redo branch when a new command arrives.
   ┌───────────────┐  run(cmd)   ┌─────────────────────────┐
   │ Invoker       │────────────►│ Command                 │
   │ button, queue,│◄────────────│  + execute()            │
   │ cron, worker  │  ok / error │  + undo()   (optional)  │
   └──────┬────────┘             └────────────┬────────────┘
          │ push(cmd)                         │ touches
          ▼                                   ▼
  history: [c1, c2, c3, c4]            Receiver: doc.text, row
                ▲
             caret ── undo: caret--  then cmd.undo()
                    ── redo: cmd.execute()  then caret++

  New command with caret mid-history -> splice(caret), redo dies.

05 — Edit freely, run it right here

Try it: undo/redo with a macro that undoes in one step

tsdemo.ts
type Command = { readonly label: string, execute(): void, undo(): void }

const doc = { text: '' }
const history: Command[] = []
let cursor = 0

const insert = (at: number, s: string): Command => ({
  label: 'insert "' + s + '" @' + at,
  execute: () => { doc.text = doc.text.slice(0, at) + s + doc.text.slice(at) },
  undo: () => { doc.text = doc.text.slice(0, at) + doc.text.slice(at + s.length) },
})

/** Macro = composite: several keystrokes, but the user undoes only once. */
const macro = (label: string, cmds: Command[]): Command => ({
  label,
  execute: () => cmds.forEach(c => c.execute()),
  undo: () => [...cmds].reverse().forEach(c => c.undo()),
})

const log = (op: string, what: string) => console.log(op.padEnd(6) + what.padEnd(21) + '| ' + doc.text)

function run(cmd: Command) {
  cmd.execute()
  history.splice(cursor) // a new command kills everything after the cursor
  history.push(cmd)
  cursor++
  log('run', cmd.label)
}
function undo() {
  if (cursor === 0) return log('undo', '(no history left)')
  const cmd = history[--cursor]; cmd.undo(); log('undo', cmd.label)
}
function redo() {
  if (cursor === history.length) return log('redo', '(nothing left)')
  const cmd = history[cursor++]; cmd.execute(); log('redo', cmd.label)
}

run(insert(0, 'hey'))
run(insert(3, ' there'))
run(macro('rename variable', [insert(9, ' pal'), insert(13, '!')]))
undo(); undo(); redo()
run(insert(0, '>> '))
redo()
console
run   insert "hey" @0      | hey
run   insert " there" @3   | hey there
run   rename variable      | hey there pal!
undo  rename variable      | hey there
undo  insert " there" @3   | hey
redo  insert " there" @3   | hey there
run   insert ">> " @0      | >> hey there
redo  (nothing left)       | >> hey there

The same code runs on Bun: bun run demo.ts. Its output is checked automatically when the site is built.

06 — Honest about the cost

When to use it, when not to

Use it when

  • You need undo/redo, or need to revert many changes as a single action (paste, bulk refactor, "cancel 5 orders at once").
  • The work has to wait: job queues, offline queues, retry with backoff, rate limiting, scheduled runs, running in a worker.
  • You need an exact record of what happened for auditing, replay, or rebuilding state (event sourcing, migrations, multi-device sync).
  • Commands are created in one place and run in another: the UI creates them, a worker runs them, the server executes them. Making them objects is the only way to ship them across.
  • The UI needs to know whether a command can run before running it (canExecute) to enable/disable a button, or needs to preview a change before applying it.

Don't use it when

  • Over-engineering. A pure function, called immediately, no undo, no queue, no log? Write a function. Command only pays off when the action has to outlive the call — otherwise you're paying for an abstraction you never use.
  • Not every command has an inverse. Sending email, charging money, partner webhooks: don't stuff a fake undo() into the interface. Declare undo?() and use compensation (a new command that neutralises the effect) instead of reverting.
  • Commands hold old references and positions. With co-editing, autosave, or anyone else editing between creating a command and undoing it, at: 3 may point somewhere else. Safe undo needs transforms (OT/CRDT), not a simple inverse.
  • History is a legal memory leak: a thousand big commands = your user's RAM. Cap the depth (every real editor does), or store diffs/inverses instead of snapshots.
  • Once a command has been sent to the server, undoing it locally is meaningless — the real state lives on the server. At that point the command becomes an API contract between both sides, and changing its shape is a breaking change for commands already sitting in the DB.

07 — You have met it already, just not by name

In real code

Redux / Pinia: dispatch(action)

An action is a plain-data command { type, payload }; the reducer is the receiver; dispatch is the invoker. Because actions are serialisable objects, Redux DevTools can do time-travel, replay and action diffing — three things that are only possible when the "thing to do" is data rather than a closure.

Job queues in Node: BullMQ, graphile-worker, queueMicrotask

A job is a serialised command: a command name + parameters. A worker in another process calls execute() on it, while retry/backoff/attempts/offline all live in the invoker. Same structure at micro scale: queueMicrotask(fn), requestIdleCallback(fn), setTimeout(fn) — you hand a command to an invoker to run later.

Editor history: ProseMirror, Slate, Monaco/CodeMirror

In ProseMirror every Step has invert(doc); the history plugin keeps transactions for undo/redo. Slate computes the inverse of an Operation. CodeMirror/Monaco manage ChangeSets/edit ops. Ctrl+Z reverts a whole multi-line paste because many ops are grouped into one command — a macro command.

document.execCommand(commandId)

An old browser API whose name says it all: you send a command description ("bold", "insertImage") to the browser — the receiver is the browser's internal editor, the invoker is the browser, and the browser owns undo. It was deprecated because too much was abstracted out of your control — a lesson about Command when you don't own the receiver.

08 — Try it yourself

Exercise

Write an `updateStatus(id, next)` command for an admin page: `execute()` changes an order's status, `undo()` restores the **old** status, and `label` is clear enough to be the undo button tooltip. Then run it in the same history as the text commands above and show that an `updateStatus` macro undoes as one.

Hints, open them one at a time:

  1. When should the old status be read: when the command is built, or in execute()? In which situation is each choice correct?
  2. label should include the id plus both the old and the new value. A good undo tooltip tells you "what it will go back to".
  3. The macro doesn't need to know about updateStatus — it only needs a Command[]. That's why two different kinds of command fit in the same history.

The factory updateStatus(id, next) reads before when it is called (parameters frozen), and returns a command whose execute writes the new value and whose undo writes before back. Since it matches the Command contract, history and macro accept it without changing a line. If someone else may edit concurrently, move the before read into execute() and keep it in the closure of that particular run.

tsexercise.ts
type Order = { id: string, status: string }
const db = new Map<string, Order>([['o-1', { id: 'o-1', status: 'new' }]])

const updateStatus = (id: string, next: string): Command => {
  const before = db.get(id)?.status ?? '(does not exist)'   // frozen at creation
  return {
    label: id + ': ' + before + ' -> ' + next,
    execute: () => { db.set(id, { id, status: next }) },
    undo: () => { db.set(id, { id, status: before }) },
  }
}

run(updateStatus('o-1', 'paid'))              // o-1: new -> paid
run(updateStatus('o-1', 'shipped'))           // o-1: paid -> shipped
undo()                                        // back to paid
run(macro('bulk cancel', [
  updateStatus('o-1', 'cancelled'),
  updateStatus('o-2', 'cancelled'),
]))
undo()                                        // the whole batch reverts, one click

09 — Read them in pairs to see the essence

Related patterns

  • MementoMemento stores **state** to go back to; Command stores **actions** to do/undo. A Command's `undo()` often holds a Memento inside — these two are a classic pair.
  • CompositeA macro command is Composite in the literal sense: a command and a list of commands share one contract, so the invoker treats them the same and macros can nest macros.
  • StrategyStrategy answers "**how** do we do this" and is picked then run. Command answers "what, with which parameters" and may never run at all (cancelled, replayed).
  • BuilderBoth bundle something into an object for later. Builder accumulates **data** and builds once; Command captures **behaviour** that can run many times, be queued, or be undone.