📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the Command pattern? Explain how representing a request as an object enables queuing, retries, undo and auditing, the difference between a GoF command with Execute and a modern command message with a separate handler, and how commands differ from events.

Command intent and structure (invoker, command, receiver), GoF Execute/Undo commands for undo stacks and macros, modern serialisable command records with ICommandHandler<T>, queuing with Channel<T> or a broker, retries and idempotency keys, audit logs, WPF/MAUI ICommand, and commands vs events.

Intermediate Theory Intermediate channels command cqrs design-patterns undo

🎯 Key points

  • Command turns a request into an object, so it can be stored, queued, logged, retried or undone instead of executed immediately
  • GoF roles: Invoker triggers, Command holds what to do, Receiver does the work; the invoker knows only ICommand.Execute
  • Undo: commands implement Execute and Undo and are pushed on a stack; macro commands compose several commands
  • Modern style splits data from behaviour: an immutable record (PlaceOrder) plus an ICommandHandler<PlaceOrder>, so the command serialises to a queue or audit log
  • Queuing: Channel<T> in-process with a BackgroundService consumer, or Azure Service Bus across processes
  • Retries need idempotency: give each command a CommandId and have the handler ignore duplicates
  • Command = imperative intent, one handler, can be rejected (PlaceOrder); event = past fact, zero or many handlers (OrderPlaced)
  • .NET examples: WPF/MAUI ICommand (Execute, CanExecute), MediatR IRequest, DbCommand encapsulating a database request

⏱ 30-second answer

Command turns a request into an object. Once "place this order" or "rename this file" is data rather than a method call, you can queue it, retry it, log it for audit, or undo it.

  • GoF style: the command has Execute() (and Undo()); an invoker runs it without knowing what it does. Good for undo stacks and macros.
  • Modern style: an immutable record (PlaceOrder) plus a separate handler (ICommandHandler<PlaceOrder>). Splitting data from behaviour lets the command be serialised to a Channel<T>, Azure Service Bus or an audit table.

A command is an imperative request with one handler that may reject it; an event is a past-tense fact with any number of handlers.

The trade-off: an extra type per operation and indirection, so plain method calls are fine when you need none of queuing, retry, undo or audit.

🗣 Full answer (senior)

How I would answer this in an interview

"Command means turning a request into an object. Instead of calling orderService.Place(customerId, items) directly, I create a PlaceOrder object that carries everything needed to do the work. That sounds trivial, but once the request is data you can do things with it that you can't do with a method call: put it in a queue to run later, retry it after a transient failure, write it to an audit log, or keep it on a stack so you can undo it.

There are two flavours. The original GoF version puts behaviour on the command: an ICommand with Execute and often Undo, and an invoker, like a toolbar button or a job runner, that calls Execute without knowing what it does. WPF and MAUI's ICommand with Execute and CanExecute is exactly that, and it's how you build undo and redo in an editor: push each executed command on a stack, pop and call Undo. The modern server-side version splits data from behaviour: PlaceOrder is an immutable record, and PlaceOrderHandler implements ICommandHandler<PlaceOrder>. The reason is serialisation: a record with only data can go into a Channel<T>, an Azure Service Bus message or an audit table, while a command object holding a DbContext can't. That's also what MediatR's IRequest and its handlers are.

The mistake I see is confusing commands with events. A command is imperative, 'place this order', it has exactly one handler, and that handler can say no. An event is a past-tense fact, 'order placed', and any number of handlers can react to it or none. The other mistake is forgetting that queuing and retry mean a command can run twice, so I give every command a CommandId and make the handler idempotent. A command is a request you can hold in your hand; that's what makes it queueable, retryable and auditable."


Participants

Role GoF example Modern server example
Command RenameFileCommand : ICommand record PlaceOrder(...)
Receiver FileSystem OrdersDbContext, payment client
Invoker Button, undo manager Endpoint, queue consumer, scheduler
Handler (behaviour lives on the command) PlaceOrderHandler : ICommandHandler<PlaceOrder>

What making a request an object buys you

Capability How the command enables it
Queuing Write the record to a Channel<T> or broker; a consumer handles it later
Retry Re-dispatch the same object; CommandId makes it idempotent
Undo Command stores what it needs to reverse itself; undo stack pops it
Audit Serialise the command with who and when before handling
Macros / batching A composite command runs a list of commands

Command vs event

Command Event
Tense Imperative: PlaceOrder Past: OrderPlaced
Handlers Exactly one Zero or many
Can be rejected Yes (validation, business rules) No, it already happened
Sender expects A result or an acknowledgement Nothing

Production example

A bulk price-update screen called the pricing service synchronously and timed out above about 5,000 SKUs. Turning each update into an UpdatePrice command record, written to a bounded Channel<T> and handled by a BackgroundService, made the request return in under 200 ms. Each command carried a CommandId and the user, which gave the merchandising team an audit trail and made retries after a database failover safe.

🔍 What the interviewer is checking

Checks that the candidate understands why making a request an object matters, knows both the GoF and modern command shapes, and distinguishes commands from events.

Green flags

  • Explains queuing, retry, undo and audit as consequences of reifying the request.
  • Separates data-only command records from handlers and explains why (serialisation).
  • Mentions idempotency for retried commands.
  • Clearly distinguishes commands from events.

Red flags

  • Describes Command as "a class with an Execute method" with no consequences.
  • Puts services or DbContext inside queued commands.
  • Treats commands and events as interchangeable.

📚 Learn in depth

1. Structure (GoF)

Client ──creates──▶ ConcreteCommand ── receiver: Receiver
                     Execute() { receiver.Action(state) }
                     Undo()    { receiver.Reverse(state) }
                              ▲
                    «interface» ICommand
                              │
Invoker ── holds/queues ICommand, calls Execute() without knowing what it does

The invoker is decoupled from both the receiver and the operation. That is what lets a toolbar button, a keyboard shortcut and a scripting engine all trigger the same command.

2. Undo and redo

Each command records enough state to reverse itself (the old name, the removed line, the previous price). The undo manager keeps two stacks:

Execute(cmd):  cmd.Execute(); undo.Push(cmd); redo.Clear()
Undo():        cmd = undo.Pop(); cmd.Undo(); redo.Push(cmd)
Redo():        cmd = redo.Pop(); cmd.Execute(); undo.Push(cmd)

Macro commands are Composite applied to Command: Execute runs children in order, Undo reverses them in reverse order.

3. Data and behaviour split

Server systems rarely need Undo on the object, but they need commands to cross boundaries: a queue, another process, a database row. Objects holding a DbContext or HttpClient can't be serialised, so the command becomes a record of data and the behaviour moves to a handler resolved from DI:

PlaceOrder (record) ──dispatch──▶ ICommandHandler<PlaceOrder> ──▶ DbContext, payment API

This is the shape CQRS uses for its write side, and what MediatR's IRequest<T> and IRequestHandler<T, TResult> implement.

4. Queuing

  • In-process: Channel.CreateBounded<UpdatePrice>(capacity) gives back-pressure; a BackgroundService reads with ReadAllAsync and calls the handler inside a new DI scope. Work is lost if the process dies.
  • Out-of-process: serialise the command to Azure Service Bus or a database outbox for durability, retries and dead-lettering.

5. Retries and idempotency

Any queue gives at-least-once delivery, so a handler can see the same command twice. Give each command a CommandId (a GUID created by the sender) and record processed ids in the same transaction as the work, or design the operation to be naturally idempotent (set price to X, not add Y).

6. Framework examples

API Command role
WPF / MAUI ICommand Execute(object?), CanExecute(object?), CanExecuteChanged; bound to buttons
DbCommand / SqlCommand Encapsulates a database request (text, parameters) executed later
MediatR IRequest<T> Request object dispatched to one handler
ThreadPool.QueueUserWorkItem, Task.Run Work item as a delegate, queued for later execution

7. Costs

One type per operation, plus a dispatch step. For CRUD endpoints with no queuing, retry, undo or audit, a command object adds files without adding capability.

Try it yourself

  1. Build an undo/redo stack for a text editor with InsertText and DeleteText commands.
  2. Write a MacroCommand and check that undo reverses children in reverse order.
  3. Put UpdatePrice records through a bounded Channel<T> and a BackgroundService; observe back-pressure when capacity is 10.
  4. Dispatch the same command twice and make the handler idempotent using CommandId.
  5. Serialise commands to JSON before handling and build a simple audit log.

💻 Code

GoF-style commands with undo, then command records with a handler and an in-process queue.

namespace Editor;

public interface IUndoableCommand
{
    void Execute();
    void Undo();
}

public sealed class Document
{
    private readonly System.Text.StringBuilder _text = new();
    public string Text => _text.ToString();
    public void Insert(int at, string s) => _text.Insert(at, s);
    public void Remove(int at, int length) => _text.Remove(at, length);
}

// The command stores what it needs to reverse itself
public sealed class InsertText(Document doc, int at, string text) : IUndoableCommand
{
    public void Execute() => doc.Insert(at, text);
    public void Undo() => doc.Remove(at, text.Length);
}

// Invoker: runs commands without knowing what they do
public sealed class UndoManager
{
    private readonly Stack<IUndoableCommand> _undo = new();
    private readonly Stack<IUndoableCommand> _redo = new();

    public void Run(IUndoableCommand cmd) { cmd.Execute(); _undo.Push(cmd); _redo.Clear(); }
    public void Undo() { if (_undo.TryPop(out var c)) { c.Undo(); _redo.Push(c); } }
    public void Redo() { if (_redo.TryPop(out var c)) { c.Execute(); _undo.Push(c); } }
}
namespace Pricing;

using System.Threading.Channels;

// Modern style: the command is data only, so it can be queued, logged and retried
public sealed record UpdatePrice(Guid CommandId, string Sku, decimal NewPrice, string RequestedBy);

public interface ICommandHandler<in TCommand>
{
    Task HandleAsync(TCommand command, CancellationToken ct);
}

public sealed class UpdatePriceHandler(PricingDbContext db, ILogger<UpdatePriceHandler> logger)
    : ICommandHandler<UpdatePrice>
{
    public async Task HandleAsync(UpdatePrice cmd, CancellationToken ct)
    {
        // Idempotent: a retried command with the same id is ignored
        if (await db.ProcessedCommands.AnyAsync(p => p.Id == cmd.CommandId, ct)) return;

        var product = await db.Products.SingleAsync(p => p.Sku == cmd.Sku, ct);
        product.Price = cmd.NewPrice;     // set, not add: naturally idempotent too
        db.ProcessedCommands.Add(new ProcessedCommand(cmd.CommandId, DateTimeOffset.UtcNow));
        await db.SaveChangesAsync(ct);    // work and dedup record in one transaction

        logger.LogInformation("Price for {Sku} set to {Price} by {User}", cmd.Sku, cmd.NewPrice, cmd.RequestedBy);
    }
}

// Invoker: a background consumer of an in-process queue
public sealed class PriceCommandWorker(Channel<UpdatePrice> queue, IServiceScopeFactory scopes) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (var cmd in queue.Reader.ReadAllAsync(stoppingToken))
        {
            await using var scope = scopes.CreateAsyncScope();   // handler and DbContext are scoped
            var handler = scope.ServiceProvider.GetRequiredService<ICommandHandler<UpdatePrice>>();
            await handler.HandleAsync(cmd, stoppingToken);
        }
    }
}
// Program.cs
builder.Services.AddSingleton(Channel.CreateBounded<UpdatePrice>(new BoundedChannelOptions(1_000)
{
    FullMode = BoundedChannelFullMode.Wait          // back-pressure instead of unbounded memory
}));
builder.Services.AddScoped<ICommandHandler<UpdatePrice>, UpdatePriceHandler>();
builder.Services.AddHostedService<PriceCommandWorker>();

app.MapPost("/prices", async (UpdatePriceRequest[] updates, Channel<UpdatePrice> queue, HttpContext http, CancellationToken ct) =>
{
    var user = http.User.Identity?.Name ?? "unknown";
    foreach (var u in updates)
        await queue.Writer.WriteAsync(new UpdatePrice(Guid.NewGuid(), u.Sku, u.Price, user), ct);
    return Results.Accepted();
});

public sealed record UpdatePriceRequest(string Sku, decimal Price);

⚠ Common mistakes

  • Mistake: Putting a DbContext or HttpClient inside a command that is meant to be queued. Why it is wrong: It can't be serialised and it outlives its scope. Instead: Keep commands as data-only records and resolve handlers per message in a new scope.
  • Mistake: Queuing or retrying commands without an idempotency key. Why it is wrong: At-least-once delivery runs some commands twice: double charges, duplicate orders. Instead: Give each command a CommandId and record processed ids in the same transaction.
  • Mistake: Naming commands like events (OrderPlaced) or publishing commands to many handlers. Why it is wrong: It blurs who is responsible and whether rejection is possible. Instead: Imperative names and one handler for commands; past-tense names and many handlers for events.
  • Mistake: Using an in-process Channel<T> for work that must not be lost. Why it is wrong: Queued commands vanish on a crash or deploy. Instead: Use a durable queue (Service Bus, outbox table) for critical work.
  • Mistake: An unbounded in-process queue. Why it is wrong: A slow handler lets memory grow until the process dies. Instead: Channel.CreateBounded with FullMode.Wait for back-pressure.
  • Mistake: An Undo that recomputes state instead of storing what changed. Why it is wrong: Later commands may have changed the data, so undo restores the wrong value. Instead: Capture the previous state when executing.
  • Mistake: Wrapping every CRUD call in a command and handler. Why it is wrong: Extra types and indirection with no queuing, retry, undo or audit benefit. Instead: Call a service method directly until one of those needs appears.

🏛 Senior insight: trade-offs

I use the term Command mostly as a design signal: once a request needs to be stored, delayed, retried or reviewed, make it a data-only record with a single handler. The pattern itself is simple; the senior part is the consequences of making work asynchronous: idempotency, durability, back-pressure and observability (correlate the command id through logs and traces).

Option When it fits Cost When not to
Direct method call Synchronous request, no audit or retry needs None Work must be queued or replayed
GoF command with Execute/Undo Editors, UI actions, undo/redo, macros State capture per command Server workflows crossing process boundaries
Command record + handler Queues, audit, CQRS write side One record and handler per operation Simple CRUD
In-process Channel<T> Smoothing bursts, best-effort background work Lost on crash Work that must be durable
Broker message (Service Bus) Durable, cross-service, retries, dead-letter Infrastructure, eventual consistency Low-latency synchronous responses

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions queuing commands with Channel<T> or a background worker Why: Checks building a bounded producer/consumer pipeline for queued commands
    How to answer

    System.Threading.Channels provides fast, async-friendly queues for passing data between producers and consumers. Channel.CreateBounded<T>(capacity) gives backpressure: when full, WriteAsync waits (or drops items, depending on BoundedChannelFullMode). Channel.CreateUnbounded<T>() never blocks writers but can grow without limit. Writers call Complete() when done; readers loop with await foreach (var x in reader.ReadAllAsync(ct)) and finish when the channel is completed and empty. Options such as SingleReader and SingleWriter enable faster internal implementations. Channels are the standard building block for in-process background queues and pipelines.

  2. When: Candidate suggests running commands in the background Why: Checks safe background work in ASP.NET Core instead of fire-and-forget
    How to answer

    Fire-and-forget means starting a task and not awaiting it, such as _ = SendEmailAsync(). The risks are: exceptions are never observed, scoped services like DbContext are disposed when the request ends (giving ObjectDisposedException), work is lost on shutdown or crash, there is no limit on how much work piles up, and HttpContext may be used after the request is gone. In ASP.NET Core, hand the work to a queue (Channel<T>) processed by a BackgroundService that creates its own scope, logs failures and drains on shutdown. If the work must not be lost, use a durable queue or an outbox table.

  3. When: Candidate mentions MediatR's IRequest and handlers as commands Why: Checks MediatR as a command dispatcher and when it is worth it
    How to answer

    The GoF Mediator stops objects talking to each other directly: colleagues send messages to a mediator, which turns many-to-many coupling into many-to-one (a dialog coordinating its controls).

    MediatR is really an in-process request dispatcher: Send(IRequest<T>) goes to exactly one handler, Publish(INotification) to many, and IPipelineBehavior wraps every handler with validation, logging or transactions.

    It's indirection for nothing when an endpoint just sends to a handler that calls a repository: injecting the handler gives the same decoupling, and "go to definition" still works.

    Licensing: since v13 (July 2025) MediatR is dual RPL-1.5 / commercial under Lucky Penny Software, free (Community edition) under US$5M revenue; 12.5.0 is the last Apache 2.0 version.

    Alternatives: direct handler injection with decorators, or a source-generated mediator. The trade-off is uniform pipelines vs traceable, explicit code.

↩ Usually asked after

More in Behavioral Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me