Command Pattern: Turning Operations into Objects
The Command Pattern represents an operation as an object, separating what needs to be done from when and how it executes. Learn how to implement commands in TypeScript, connect them to background jobs, reason about retries and idempotency, and understand when undo and audit logging require additional infrastructure.
Table of Contents
- Introduction
- 1. The Problem: Actions Are Tightly Coupled to Their Execution
- 2. The Core Idea Behind the Command Pattern
- 3. Implementing Command in TypeScript
- 4. Commands, Queues, Retries, and Background Jobs
- 5. Undo, Audit Logs, and Reversible Operations
- 6. Command vs. Strategy, Callback, and Message Queue
- 7. Common Command Pattern Mistakes
- 8. When Should You Use the Command Pattern?
- Summary
Introduction
Most applications execute operations directly.
A controller calls a service. The service updates a database. Another service sends a notification. The request finishes, and the application returns a response.
This is often the simplest and most appropriate design.
However, requirements change when an operation must be scheduled for later, placed in a queue, retried after a failure, recorded for auditing, or potentially reversed.
If the operation exists only as a direct method call, the application may need to add execution-specific logic throughout its services. Background workers may duplicate business logic. Audit requirements may introduce additional dependencies. Retry behavior may become entangled with the operation itself.
The Command Pattern addresses this problem by representing an operation as an object.
Instead of immediately invoking a method, the application creates a command that describes an action and exposes a way to execute it.
This separation allows the application to decide when and where the operation runs without requiring the caller to understand its implementation.
The important distinction is that a command is more than a method call wrapped in a class. It becomes valuable when the application needs to treat an operation as an independent unit that can be passed around, stored, scheduled, inspected, or executed by another component.
1. The Problem: Actions Are Tightly Coupled to Their Execution
Imagine an e-commerce application that creates an order and sends a confirmation email.
A simple implementation might look like this:
class OrderService {
constructor(
private readonly repository: OrderRepository,
private readonly emailService: EmailService,
) {}
async createOrder(input: CreateOrderInput) {
const order = await this.repository.create(input);
await this.emailService.sendOrderConfirmation(order);
return order;
}
}For a small application, this implementation may be perfectly reasonable.
But suppose the requirements evolve:
- Email delivery must happen asynchronously.
- Failed notifications should be retried.
- Every notification attempt must be recorded.
- Certain operations must be processed by a background worker.
- Administrators need to inspect or replay failed jobs.
The existing service now has to accommodate both the business operation and its execution requirements.
One response is to add more methods:
async createOrderAndNotify(input: CreateOrderInput) {
// Create the order and send the email.
}
async createOrderAndQueueNotification(input: CreateOrderInput) {
// Create the order and enqueue a notification.
}
async retryOrderNotification(orderId: string) {
// Find the order and send the email again.
}This can work initially, but it risks duplicating operation logic and spreading execution decisions across the application.
The deeper problem is that the application treats the operation and the mechanism used to execute it as one thing.
We want to represent the operation independently so that another component can decide how and when it should run.
2. The Core Idea Behind the Command Pattern
The Command Pattern encapsulates a request as an object.
A typical implementation has four conceptual participants:
- Command: Defines the operation that can be executed.
- Concrete command: Implements the operation by coordinating the required dependencies.
- Invoker: Decides when to execute the command.
- Receiver: Performs the actual business or infrastructure work.
The relationship looks like this:
flowchart TD
Caller -->|creates and submits| Invoker
Invoker -->|calls execute| Command
Command -->|delegates work to| ReceiverThe caller does not need to know how the operation is performed. It creates or receives a command, then passes it to the component responsible for execution.
For example, a web request might create a command and submit it to a job scheduler. A worker can execute that command later without reproducing the underlying business logic.
The command acts as an explicit boundary between describing an operation and executing an operation.
This separation is useful because execution can evolve independently. A command might be executed immediately today and dispatched to a background worker tomorrow.
However, the pattern does not automatically provide persistence, retries, distributed execution, or exactly-once processing. Those capabilities require additional infrastructure and carefully defined semantics.
3. Implementing Command in TypeScript
Let's begin with a minimal implementation and add complexity only when it is justified.
Step 1: Define a command contract
A simple command interface might look like this:
interface Command<TResult> {
execute(): Promise<TResult>;
}The command exposes one operation: execute().
The generic result type allows different commands to return different results while preserving type safety.
Not every command needs to return a value. A notification command, for example, might use Command<void>.
Step 2: Implement a concrete command
Suppose an application needs to send an order confirmation.
interface OrderRepository {
findById(orderId: string): Promise<Order | null>;
}
interface EmailService {
sendOrderConfirmation(order: Order): Promise<void>;
}
class SendOrderConfirmationCommand
implements Command<void>
{
constructor(
private readonly orderId: string,
private readonly orders: OrderRepository,
private readonly email: EmailService,
) {}
async execute(): Promise<void> {
const order = await this.orders.findById(
this.orderId,
);
if (!order) {
throw new Error(
`Order not found: ${this.orderId}`,
);
}
await this.email.sendOrderConfirmation(order);
}
}The command contains the information needed to perform the operation and coordinates the relevant dependencies.
The receiver responsibilities remain in the repository and email service. The command does not need to reimplement database access or email delivery.
Notice that the command stores an orderId rather than a full order object. This can reduce the amount of state captured when the command is created and ensures the command retrieves the current order when it executes.
That choice is not universally correct. Some operations must act on a snapshot of the data as it existed when the request was created. In those cases, the command should explicitly capture the required immutable data instead.
Step 3: Introduce an invoker
The invoker is responsible for triggering execution.
class CommandInvoker {
async execute<TResult>(
command: Command<TResult>,
): Promise<TResult> {
return command.execute();
}
}A caller can now submit the command without knowing its internal implementation:
const command = new SendOrderConfirmationCommand(
orderId,
orderRepository,
emailService,
);
const invoker = new CommandInvoker();
await invoker.execute(command);At this point, the invoker adds little value over a direct method call. That is intentional.
The minimal implementation demonstrates the separation, but it does not yet justify an additional abstraction on its own.
The pattern becomes more useful when the invoker has a real responsibility, such as logging execution, applying a policy, scheduling work, or coordinating command dispatch.
Step 4: Add execution-level behavior
For example, an invoker can record how long a command takes:
class InstrumentedCommandInvoker {
async execute<TResult>(
command: Command<TResult>,
): Promise<TResult> {
const startedAt = Date.now();
try {
return await command.execute();
} finally {
recordCommandDuration(
Date.now() - startedAt,
);
}
}
}Here, recordCommandDuration() represents an application-specific metrics function.
The command's implementation remains focused on the operation, while the invoker manages execution-level instrumentation.
Other policies can be introduced when needed, but avoid turning a simple invoker into an all-purpose framework before the application has real requirements for one.
4. Commands, Queues, Retries, and Background Jobs
One of the most useful applications of the Command Pattern is separating business operations from the process that triggers them.
However, a command object in memory and a persistent background job are not the same thing.
4.1. From immediate execution to deferred execution
An application may initially execute a command directly:
await command.execute();Later, it may want to submit the operation to a queue:
await jobQueue.enqueue({
type: "send-order-confirmation",
payload: {
orderId,
},
});The queue example uses a serialized job representation rather than the command instance itself.
This distinction matters. A command object may contain service instances, database connections, or other runtime dependencies that cannot be safely serialized and transferred to another process.
A worker can reconstruct the command from a stable job type and payload:
async function handleJob(job: {
type: string;
payload: unknown;
}) {
switch (job.type) {
case "send-order-confirmation": {
const payload = parseOrderConfirmationPayload(
job.payload,
);
const command =
new SendOrderConfirmationCommand(
payload.orderId,
orderRepository,
emailService,
);
await command.execute();
return;
}
default:
throw new Error(
`Unsupported job type: ${job.type}`,
);
}
}parseOrderConfirmationPayload() represents runtime validation of the untrusted job payload.
In a production system, the dispatch mechanism should validate payloads, version job schemas where necessary, and define what happens when a job type is no longer supported.
4.2. Retries require more than a command
A failed command can often be executed again, but whether that is safe depends on the operation.
Consider sending a payment request to an external provider. The provider may process the request successfully while the network connection fails before the application receives the response.
The application cannot safely conclude that the payment failed.
Blindly retrying could create a duplicate charge.
For retryable operations, consider:
- Whether the operation is idempotent.
- Whether the external system supports idempotency keys.
- Which errors are retryable.
- Whether the previous attempt's outcome is known.
- How many attempts are allowed.
- How retry delays and dead-letter handling work.
A command object gives the system a unit of work to execute. It does not determine whether repeated execution is safe.
4.3. Keep job state outside the command when appropriate
A persistent job system may track:
type JobStatus =
| "pending"
| "processing"
| "completed"
| "failed";The queue or job repository can store the job's status, attempt count, timestamps, and failure details.
This is generally preferable to making the command instance itself responsible for durable execution state.
A worker may restart, a job may be processed by another machine, or the command may be reconstructed from a serialized payload. In-memory object state is not a reliable substitute for persistent job state.
4.4. Avoid losing the operation between a database write and queue submission
Consider an order workflow that first saves an order to the database and then enqueues a notification job.
If the database transaction succeeds but queue submission fails, the order exists while the notification job may never be created.
This is a reliability problem that the Command Pattern alone does not solve.
For systems where this failure matters, a transactional outbox can record the event or pending work in the same database transaction as the business change. A separate publisher then forwards the outbox entry to the queue.
The command describes the operation. The outbox and queue provide durability and delivery mechanisms around it.
Keeping these responsibilities separate prevents a design pattern from being mistaken for a complete distributed-systems solution.
5. Undo, Audit Logs, and Reversible Operations
Commands can also help when an application needs to record which operations were requested or support reversing certain actions.
5.1. Supporting undo
A command can expose an inverse operation:
interface ReversibleCommand {
execute(): Promise<void>;
undo(): Promise<void>;
}For example, a command that changes a user's display name might store the previous value so it can restore it later.
class ChangeDisplayNameCommand
implements ReversibleCommand
{
private previousName: string | null = null;
constructor(
private readonly userId: string,
private readonly newName: string,
private readonly users: UserRepository,
) {}
async execute(): Promise<void> {
const user = await this.users.findById(
this.userId,
);
if (!user) {
throw new Error("User not found");
}
this.previousName = user.displayName;
await this.users.updateDisplayName(
this.userId,
this.newName,
);
}
async undo(): Promise<void> {
if (this.previousName === null) {
throw new Error(
"Command has not been executed",
);
}
await this.users.updateDisplayName(
this.userId,
this.previousName,
);
}
}This example illustrates the concept, but a production implementation needs to consider repeated execution, concurrent updates, and whether the previous value is still valid when undo is requested.
It also demonstrates a limitation: the command's undo state is stored in memory. It will not survive process restarts unless the necessary state is persisted.
5.2. Not every operation is reversible
Changing a display name may be reversible. Sending an email, issuing a refund, or delivering a physical package is not necessarily reversible in the same sense.
For some operations, the best available compensation is another operation.
For example, a completed booking might be compensated by issuing a cancellation request. This does not erase the original booking; it creates a new business action with its own rules and failure modes.
In distributed workflows, these compensating actions are often part of a Saga rather than a simple undo stack.
Do not add an undo() method to every command merely because the pattern makes it possible. Reversibility is a business capability, not an automatic property of the Command Pattern.
5.3. Commands and audit logging
A command can provide a useful place to identify the requested operation:
interface AuditableCommand<TResult>
extends Command<TResult> {
readonly commandType: string;
}An execution layer can record the command type, actor, correlation ID, outcome, and relevant timestamps.
However, the command payload may contain personal data, credentials, payment details, or other sensitive information.
Audit records should capture only what is needed, with appropriate access controls and retention rules. Logging an entire serialized command by default can create a serious data exposure risk.
For durable audit requirements, use a persistent audit mechanism with clearly defined guarantees rather than relying solely on an in-memory command object.
6. Command vs. Strategy, Callback, and Message Queue
The Command Pattern is easy to confuse with other mechanisms because each can represent or trigger an action.
| Concept | Primary purpose | Example |
|---|---|---|
| Command | Represent an operation as an object | SendOrderConfirmationCommand |
| Strategy | Encapsulate an interchangeable algorithm | Select a pricing calculation strategy |
| Callback | Pass executable behavior to another function | onSuccess() |
| Message queue | Transport and manage work between producers and consumers | Deliver a job to a background worker |
A Strategy answers: which algorithm should perform this task?
A Command answers: which operation should be executed?
A callback is often simply a function reference. It may be sufficient when the application only needs to invoke behavior at a particular point. A command object becomes more useful when the operation needs explicit identity, captured parameters, execution policies, or lifecycle management.
A message queue provides infrastructure for delivering and managing work. A command can be executed through a queue, but the queue itself is not the Command Pattern.
These concepts can be combined. A command may use a Strategy internally, be submitted through a queue, and trigger callbacks when processing completes.
The design should reflect the responsibility of each component rather than forcing every operation into a command class.
7. Common Command Pattern Mistakes
7.1. Wrapping every method in a command
A class that contains only one line of delegation does not automatically improve the design.
class GetUserCommand implements Command<User> {
constructor(
private readonly users: UserRepository,
) {}
execute(): Promise<User> {
return this.users.getCurrentUser();
}
}This may be useful if commands are part of a consistent application architecture or need execution policies. Otherwise, it may simply add indirection.
Use the pattern where the operation needs to be represented independently, not as a rule that every service method must have a matching command class.
7.2. Putting all business logic in the invoker
The invoker should coordinate execution, not become a central service that knows every operation's business rules.
If the invoker contains large conditional blocks for every command type, the design has merely moved the original coupling into a different class.
Keep command-specific behavior in the command or its collaborating domain services. Keep shared execution policies in the invoker or execution infrastructure.
7.3. Treating an in-memory command as a durable job
An object containing service instances cannot generally be persisted or sent to another process as-is.
For background execution, define a serializable message or job payload and reconstruct the command inside the worker.
Also consider payload versioning, validation, authorization, and the lifetime of dependencies.
7.4. Assuming retries are automatically safe
A command may execute more than once because of worker crashes, timeouts, or queue delivery guarantees.
If the operation changes external state, repeated execution may have consequences.
Use idempotency mechanisms, deduplication, transactional boundaries, or explicit recovery procedures as appropriate. The correct solution depends on the operation and the systems involved.
7.5. Making commands depend on hidden global state
A command should make its important inputs and dependencies clear.
If it reaches into global service locators or mutable application state, it becomes harder to understand, test, and reconstruct reliably.
Constructor injection or explicit execution context usually makes dependencies more visible.
7.6. Designing undo without defining business semantics
Undo is not always the exact inverse of execution. External side effects may be irreversible, and the underlying data may have changed since the original operation.
Define what reversal means for each operation, whether it is allowed, and what happens when compensation fails.
8. When Should You Use the Command Pattern?
The Command Pattern is useful when:
- Operations need to be passed between components as explicit objects.
- Execution must be separated from request handling.
- The application needs a consistent way to instrument or govern execution.
- Work may be scheduled, queued, or processed by background workers.
- Certain operations need identity, auditing, or a carefully designed compensation mechanism.
It may be unnecessary when:
- A direct function or method call is clear and sufficient.
- The operation has no meaningful lifecycle outside its immediate execution.
- Each command class merely delegates to another method without adding useful separation.
- A framework already provides an appropriate job abstraction and another command layer would duplicate it.
Before introducing the pattern, ask:
- Does the operation need to exist independently of the code that triggers it?
- Will execution policies differ from the operation's business behavior?
- Does the system need to identify, defer, record, or reconstruct the operation?
If the answers are mostly no, a direct method call is likely the better design.
If the answers are yes, a command can create a useful boundary between what the application wants done and how that work is executed.
Summary
The Command Pattern turns an operation into an explicit object that can be passed to another component for execution.
Its main benefit is separation: the caller does not need to know how the operation works, and the execution mechanism does not need to duplicate the operation's business logic.
Commands can be useful for deferred execution, background jobs, audit requirements, instrumentation, and certain reversible workflows. But each of these capabilities requires additional design decisions beyond the pattern itself.
A command does not automatically provide durability, retries, idempotency, distributed coordination, or safe undo. Those properties must be designed according to the application's actual requirements.
The goal is not to turn every method into an object. It is to represent operations explicitly when their execution needs a lifecycle of its own.
- Design Patterns
- Command Pattern
- OOP
- Programing
- Software Architecture
- Message Queue Architecture
- Background Job Processing