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

πŸ“š Interview question

Model an order lifecycle (Pending, Paid, Shipped, Delivered, Cancelled) as a state machine that rejects invalid transitions such as shipping a cancelled order. Compare a switch expression transition table, the State pattern with state classes, and the Stateless library, and show how you persist the state with EF Core safely under concurrent requests.

State pattern applied to an order aggregate: (state, trigger) switch-expression transition tables, State classes when behaviour differs per state, the Stateless library (5.20.1) with Permit/PermitIf, external state storage, OnEntry, CanFire and graph export, returning 409 for invalid transitions, persisting the status with EF Core and a rowversion concurrency token, and testing transitions.

Mid-Level Coding Intermediate concurrency design-patterns ef-core state state-machine stateless

🎯 Key points

  • State pattern: an object's behaviour depends on its state, and transitions are explicit; invalid transitions are rejected instead of silently changing a status field
  • A (state, trigger) tuple switch expression is a compact transition table; unlisted pairs fall to a discard arm that rejects the transition
  • State classes (IOrderState per state) fit when each state has substantial behaviour and rules; overkill for a pure transition table
  • Stateless (5.20.1, Feb 2026, Apache 2.0): Configure(state).Permit(trigger, dest), PermitIf guards, OnEntry/OnExit, CanFire, PermittedTriggers, DOT/Mermaid export
  • External state storage: new StateMachine<TState, TTrigger>(() => Status, s => Status = s) lets EF Core persist a plain Status column
  • Invalid transition is a domain error: return 409 Conflict (or a Result), never a 500
  • Concurrency: two requests (Cancel and Ship) can both pass the in-memory check; a rowversion concurrency token makes the second SaveChanges throw DbUpdateConcurrencyException
  • Test every allowed and forbidden transition with a table-driven theory; export the graph for reviews

⏱ 30-second answer

The State pattern makes behaviour depend on the current state and makes transitions explicit, so "ship a cancelled order" is rejected rather than a status field being overwritten.

Three implementations, from lightest:

  • A switch expression on (state, trigger): a compact, readable transition table; anything not listed is rejected.
  • State classes (IOrderState per state): worth it when each state has substantial behaviour of its own.
  • The Stateless library (5.20.1): Permit, PermitIf guards, OnEntry actions, CanFire, and graph export, with external state storage so EF Core persists a plain Status column.

Invalid transitions return 409 Conflict. Because two requests can both pass the check in memory, add a rowversion concurrency token so the second SaveChanges fails. The trade-off: a library and classes buy guards and visualisation at the cost of indirection; a switch table is often enough.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"The bug a state machine prevents is the one where any code path can set order.Status = Shipped, including on an order that was cancelled ten minutes ago. So the first thing I'd do is make Status private-set on the aggregate and only change it through methods named after the triggers: Pay, Ship, Deliver, Cancel. Each method asks one question: is this trigger allowed from the current state? If not, it's a domain error, which the API turns into a 409 Conflict, not a 500.

For how to express the rules, I'd start with the lightest option that's readable. A switch expression on the tuple (Status, trigger) is a transition table in about ten lines: (Pending, Pay) => Paid, (Paid, Ship) => Shipped, (Pending or Paid, Cancel) => Cancelled, and a discard arm that rejects everything else. If each state carries real behaviour, say a paid order can be partially refunded and a shipped order can be re-routed, then State classes are clearer: an IOrderState per state, each implementing only what it allows. When the machine grows guards, entry actions and a lot of states, I'd use Stateless: the current version is 5.20.1, released in February 2026, and it's actively maintained. You configure Permit and PermitIf per state, hook OnEntry to raise a domain event, ask CanFire to drive the UI's buttons, and export a DOT or Mermaid graph for the business to review. Its external-storage constructor reads and writes my Status property, so EF Core just persists a column.

The mistake I see is stopping at the in-memory check. Two requests load the same Paid order: one cancels, one ships, both checks pass, both save. Adding a rowversion concurrency token means the second SaveChanges throws DbUpdateConcurrencyException, and I return 409 and let the client reload. A state machine protects transitions in memory; the concurrency token protects them in the database. You need both."


The transition table

From \ Trigger Pay Ship Deliver Cancel
Pending Paid βœ— βœ— Cancelled
Paid βœ— Shipped βœ— Cancelled
Shipped βœ— βœ— Delivered βœ—
Delivered βœ— βœ— βœ— βœ—
Cancelled βœ— βœ— βœ— βœ—

Three implementations compared

Switch expression table State classes Stateless
Best for Pure transitions, few states Behaviour differs a lot per state Guards, entry/exit actions, many states, visualisation
Rules live One expression Spread across classes Fluent configuration
Guards when clauses Code in each class PermitIf(trigger, dest, guard)
Introspection Write it yourself Write it yourself CanFire, PermittedTriggers, GetInfo()
Dependency None None NuGet package

Persisting safely

Concern Approach
Column Store Status as a string (HasConversion<string>()) so data stays readable after enum reordering
Encapsulation Private setter; transitions only through methods
Concurrency [Timestamp] byte[] RowVersion (SQL Server rowversion); catch DbUpdateConcurrencyException β†’ 409
Side effects Raise a domain event on transition; publish through an outbox, not inline

Production example

An order service let three different endpoints set Status directly, and about 0.3% of cancelled orders still went to the warehouse, roughly 40 a week at peak. Moving transitions into the aggregate with a switch-expression table and a rowversion token brought shipped-after-cancel incidents to zero; the concurrency check caught about 15 racing requests a week, which now returned 409 and were retried by the client.

πŸ” What the interviewer is checking

Checks whether the candidate can model a lifecycle with explicit transitions, choose a proportionate implementation, and handle persistence and concurrency.

Green flags

  • Encapsulates the status and rejects invalid transitions as 409.
  • Compares switch table, State classes and Stateless with reasons.
  • Uses external state storage or a plain column for EF Core.
  • Raises the concurrent Cancel/Ship race and fixes it with a concurrency token.
  • Tests forbidden transitions.

Red flags

  • Public status setter with checks scattered across services.
  • Reaches for a library for three states with no guards.
  • No awareness of concurrency or side effects on transitions.

πŸ“š Learn in depth

1. The State pattern's structure

Order (context) ── state: IOrderState
   Pay()    ──▢ state = state.Pay(this)
   Ship()   ──▢ state = state.Ship(this)

Β«interfaceΒ» IOrderState: Pay, Ship, Deliver, Cancel
      β–²           β–²           β–²            β–²
  Pending       Paid       Shipped     Cancelled
  (Pay, Cancel) (Ship,     (Deliver)   (nothing)
                 Cancel)

The context delegates to its current state object, and the state object returns the next state. Unlike Strategy, the behaviour is chosen by the object itself and changes over its lifetime.

2. Switch expression as a transition table

C# tuple patterns make a table readable:

(Status, trigger) switch
{
    (Pending, Pay) => Paid,
    (Pending or Paid, Cancel) => Cancelled,
    ...
    _ => reject
}

The compiler can't check that every meaningful pair is listed (the discard arm makes it exhaustive), so a table-driven test over all state Γ— trigger pairs is the safety net. Guards go in when clauses: (Delivered, Refund) when DaysSinceDelivery <= 30 => Refunded.

3. When State classes earn their place

If states differ only in which transitions are allowed, classes add files without adding clarity. They earn their place when each state has its own behaviour: calculating what can be refunded, which fields can be edited, what the customer sees. A good test: if you'd write if (Status == ...) inside more than two or three methods, the behaviour belongs on state objects.

4. Stateless in practice

  • Configuration: machine.Configure(OrderStatus.Paid).Permit(OrderTrigger.Ship, OrderStatus.Shipped).Permit(OrderTrigger.Cancel, OrderStatus.Cancelled).
  • Guards: PermitIf(trigger, dest, () => condition, "description"); the description appears in graphs and errors.
  • Actions: OnEntry, OnExit, OnEntryFrom(trigger, ...); async variants with OnEntryAsync and FireAsync.
  • Invalid triggers: Fire throws InvalidOperationException by default; OnUnhandledTrigger lets you replace that with your own exception or a no-op.
  • Introspection: CanFire(trigger), PermittedTriggers (drive UI buttons), GetInfo() with UmlDotGraph.Format or the Mermaid exporter.
  • External state: the constructor taking a getter and setter stores state on your entity, so the machine is configured per instance but the data lives in the Status property EF Core maps.
  • Status: version 5.20.1 was released on 9 February 2026 and the project continues to publish builds; it targets .NET Standard 2.0, .NET Framework 4.6.2 and modern .NET, under the Apache 2.0 licence.

Configuring a machine per entity instance costs a few allocations; for hot paths, cache the configuration in a static factory method or use the switch table.

5. Concurrency: the part people miss

Request A: load order (Paid, v1) ── Cancel ── SaveChanges (v1 β†’ v2) βœ”
Request B: load order (Paid, v1) ── Ship   ── SaveChanges WHERE RowVersion = v1 β†’ 0 rows β†’ DbUpdateConcurrencyException

EF Core includes the original concurrency token in the UPDATE ... WHERE clause; zero rows affected means someone else changed the row. Return 409 and let the client reload, or retry the whole load-check-save once.

6. Side effects on transitions

Entering Shipped usually triggers a notification or a warehouse message. Raise a domain event from the transition and publish it via an outbox in the same transaction, so a rolled-back transition never sends an email.

Try it yourself

  1. Write a [Theory] over every (state, trigger) pair asserting allowed or rejected.
  2. Add a Refund trigger allowed within 30 days of delivery using a when guard and TimeProvider.
  3. Reimplement with Stateless, export a Mermaid graph and paste it into a pull request.
  4. Simulate two concurrent requests with two DbContext instances and confirm the second throws DbUpdateConcurrencyException.
  5. Count lines and files for the three versions and decide which you'd ship.

πŸ’» Code

The aggregate with a switch-expression transition table, a rowversion token and a 409 for invalid transitions.

namespace Orders;

using System.ComponentModel.DataAnnotations;

public enum OrderStatus { Pending, Paid, Shipped, Delivered, Cancelled }
public enum OrderTrigger { Pay, Ship, Deliver, Cancel }

public sealed class InvalidTransitionException(OrderStatus from, OrderTrigger trigger)
    : Exception($"Cannot {trigger} an order that is {from}.")
{
    public OrderStatus From { get; } = from;
    public OrderTrigger Trigger { get; } = trigger;
}

public sealed class Order
{
    public Guid Id { get; private set; } = Guid.NewGuid();
    public OrderStatus Status { get; private set; } = OrderStatus.Pending;   // only transitions change it

    [Timestamp] public byte[] RowVersion { get; private set; } = [];          // SQL Server rowversion

    public void Pay() => Fire(OrderTrigger.Pay);
    public void Ship() => Fire(OrderTrigger.Ship);
    public void Deliver() => Fire(OrderTrigger.Deliver);
    public void Cancel() => Fire(OrderTrigger.Cancel);

    public bool CanFire(OrderTrigger trigger) => Next(Status, trigger) is not null;

    private void Fire(OrderTrigger trigger) =>
        Status = Next(Status, trigger) ?? throw new InvalidTransitionException(Status, trigger);

    // The whole lifecycle in one readable table; anything unlisted is rejected
    private static OrderStatus? Next(OrderStatus from, OrderTrigger trigger) => (from, trigger) switch
    {
        (OrderStatus.Pending, OrderTrigger.Pay) => OrderStatus.Paid,
        (OrderStatus.Paid, OrderTrigger.Ship) => OrderStatus.Shipped,
        (OrderStatus.Shipped, OrderTrigger.Deliver) => OrderStatus.Delivered,
        (OrderStatus.Pending or OrderStatus.Paid, OrderTrigger.Cancel) => OrderStatus.Cancelled,
        _ => null
    };
}
// EF Core mapping and the endpoint: invalid transition β†’ 409, lost race β†’ 409
namespace Orders;

using Microsoft.EntityFrameworkCore;

public sealed class OrdersDbContext(DbContextOptions<OrdersDbContext> options) : DbContext(options)
{
    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder b) =>
        b.Entity<Order>().Property(o => o.Status).HasConversion<string>().HasMaxLength(20);   // readable, reorder-safe
}

public static class OrderEndpoints
{
    public static void MapOrderEndpoints(this WebApplication app) =>
        app.MapPost("/orders/{id:guid}/ship", async (Guid id, OrdersDbContext db, CancellationToken ct) =>
        {
            var order = await db.Orders.FindAsync([id], ct);
            if (order is null) return Results.NotFound();
            try
            {
                order.Ship();
                await db.SaveChangesAsync(ct);          // UPDATE ... WHERE Id = @id AND RowVersion = @original
                return Results.NoContent();
            }
            catch (InvalidTransitionException ex)
            {
                return Results.Problem(ex.Message, statusCode: StatusCodes.Status409Conflict);
            }
            catch (DbUpdateConcurrencyException)
            {
                return Results.Problem("The order was changed by another request. Reload and retry.",
                    statusCode: StatusCodes.Status409Conflict);
            }
        });
}
// The same lifecycle with Stateless 5.20.1, storing state on the entity
namespace Orders;

using Stateless;

public sealed class StatelessOrder
{
    public OrderStatus Status { get; private set; } = OrderStatus.Pending;
    public bool IsPaidInFull { get; set; }
    private readonly StateMachine<OrderStatus, OrderTrigger> _machine;

    public StatelessOrder()
    {
        _machine = new StateMachine<OrderStatus, OrderTrigger>(() => Status, s => Status = s);   // external storage

        _machine.Configure(OrderStatus.Pending)
            .Permit(OrderTrigger.Pay, OrderStatus.Paid)
            .Permit(OrderTrigger.Cancel, OrderStatus.Cancelled);

        _machine.Configure(OrderStatus.Paid)
            .PermitIf(OrderTrigger.Ship, OrderStatus.Shipped, () => IsPaidInFull, "paid in full")
            .Permit(OrderTrigger.Cancel, OrderStatus.Cancelled);

        _machine.Configure(OrderStatus.Shipped)
            .Permit(OrderTrigger.Deliver, OrderStatus.Delivered)
            .OnEntry(() => Console.WriteLine($"Order shipped"));   // raise a domain event here in real code

        _machine.OnUnhandledTrigger((state, trigger) => throw new InvalidTransitionException(state, trigger));
    }

    public void Fire(OrderTrigger trigger) => _machine.Fire(trigger);
    public bool CanFire(OrderTrigger trigger) => _machine.CanFire(trigger);
    public IEnumerable<OrderTrigger> PermittedTriggers => _machine.PermittedTriggers;   // drive UI buttons
    public string ToDotGraph() => Stateless.Graph.UmlDotGraph.Format(_machine.GetInfo());
}
// Table-driven test over every (state, trigger) pair
namespace Orders.Tests;

public class OrderTransitionTests
{
    public static TheoryData<OrderStatus, OrderTrigger, OrderStatus?> Cases => new()
    {
        { OrderStatus.Pending, OrderTrigger.Pay, OrderStatus.Paid },
        { OrderStatus.Pending, OrderTrigger.Ship, null },
        { OrderStatus.Paid, OrderTrigger.Ship, OrderStatus.Shipped },
        { OrderStatus.Paid, OrderTrigger.Cancel, OrderStatus.Cancelled },
        { OrderStatus.Cancelled, OrderTrigger.Ship, null },
        { OrderStatus.Delivered, OrderTrigger.Cancel, null },
    };

    [Theory, MemberData(nameof(Cases))]
    public void Transitions_follow_the_table(OrderStatus from, OrderTrigger trigger, OrderStatus? expected)
    {
        var order = OrderInState(from);
        if (expected is null)
            Assert.Throws<InvalidTransitionException>(() => Fire(order, trigger));
        else
        {
            Fire(order, trigger);
            Assert.Equal(expected, order.Status);
        }
    }

    private static void Fire(Order o, OrderTrigger t)
    {
        switch (t)
        {
            case OrderTrigger.Pay: o.Pay(); break;
            case OrderTrigger.Ship: o.Ship(); break;
            case OrderTrigger.Deliver: o.Deliver(); break;
            case OrderTrigger.Cancel: o.Cancel(); break;
        }
    }

    // Drive the aggregate through real transitions to reach a state
    private static Order OrderInState(OrderStatus target)
    {
        var o = new Order();
        switch (target)
        {
            case OrderStatus.Paid: o.Pay(); break;
            case OrderStatus.Shipped: o.Pay(); o.Ship(); break;
            case OrderStatus.Delivered: o.Pay(); o.Ship(); o.Deliver(); break;
            case OrderStatus.Cancelled: o.Cancel(); break;
        }
        return o;
    }
}

⚠ Common mistakes

  • Mistake: A public setter on Status that any service can change. Why it is wrong: Nothing stops shipping a cancelled order. Instead: Private setter; transitions only through trigger methods that check the table.
  • Mistake: Returning 500 for an invalid transition. Why it is wrong: It's a client or business-rule conflict, and 500s trigger alerts and retries. Instead: A domain exception or Result mapped to 409 Conflict.
  • Mistake: Relying on the in-memory check alone. Why it is wrong: Two concurrent requests can both pass it and both save. Instead: Add a rowversion concurrency token and handle DbUpdateConcurrencyException.
  • Mistake: Storing the enum as an integer. Why it is wrong: Reordering or inserting enum members silently changes the meaning of existing rows. Instead: HasConversion<string>() or explicit numeric values.
  • Mistake: Sending emails or messages directly inside OnEntry. Why it is wrong: If SaveChanges then fails, the customer was told something that didn't happen. Instead: Raise a domain event and publish it through an outbox.
  • Mistake: A class per state when states differ only in allowed transitions. Why it is wrong: Many files for what a ten-line table expresses. Instead: Use State classes only when states carry their own behaviour.
  • Mistake: Testing only the happy path. Why it is wrong: Forbidden transitions are the point of the machine. Instead: Table-driven tests over every state Γ— trigger pair.

πŸ› Senior insight: trade-offs

The choice of implementation matters much less than two decisions around it: making the status impossible to change except through transitions, and protecting transitions against concurrent writers. I start with a switch table, move to State classes when per-state behaviour piles up, and adopt Stateless when guards, entry actions and visualisation for non-developers justify a dependency.

Option When it fits Cost When not to
Switch expression table Up to ~8 states, pure transitions Guards and actions written by hand Many guards, entry/exit actions, nested states
State classes Behaviour differs substantially per state One class per state Only transition rules differ
Stateless Guards, actions, hierarchy, graph export, CanFire for UI Dependency; per-instance configuration A five-line table
Workflow engine / durable orchestration Long-running, multi-service processes with timers Infrastructure, operational complexity A single aggregate's lifecycle

I measure success by incidents (shipped-after-cancel, double refunds) and by how often DbUpdateConcurrencyException fires; a non-zero count proves the token is doing its job.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate implements the transitions as a tuple switch expression Why: Checks switch expressions, tuple patterns and guards used as transition tables
    How to answer

    A switch expression returns a value: status switch { Paid => "Paid", _ => "Other" }. Each arm is a pattern, an optional when guard, and an expression. There's no fall-through or break, and the first matching arm wins. The result type comes from the arms or from the target. The compiler warns with CS8509 if it isn't exhaustive, and an unmatched value throws SwitchExpressionException. Switching on a tuple like (state, trigger) gives very readable state machines. When an arm needs several statements or side effects, a classic switch statement or polymorphism is clearer.

  2. When: Candidate implements state classes behind an interface Why: Checks the difference between State and Strategy
    How to answer

    Strategy puts each variant of an algorithm behind one interface, so the code that uses it (the context) calls whichever implementation it was given instead of branching on a mode. A switch that grows with every new discount, carrier or export format becomes a set of small classes, and adding a variant means adding a class, not editing the switch (Open/Closed).

    .NET uses it everywhere: IComparer<T> in List<T>.Sort, IEqualityComparer<T> in Dictionary, StringComparer.OrdinalIgnoreCase, JsonNamingPolicy.

    • In DI, register several implementations and inject IEnumerable<IStrategy>, or use keyed services (.NET 8+), to pick one by key.
    • For one small function with no dependencies, a Func<T, TResult> delegate is a strategy without the ceremony.

    The trade-off: more types and indirection, so a short, stable switch is often clearer.

  3. When: Candidate uses or/when patterns in the table Why: Checks pattern-matching features and when they beat polymorphism
    How to answer

    C# patterns now cover most data checks. There are type, constant and null patterns, relational ones like >= 100, logical and, or and not combinators, and property patterns, including extended ones like { Customer.Address.State: "NSW" }. There are also positional patterns that use Deconstruct, var and discard patterns, and list patterns like [first, .., last]. The compiler turns a switch into an efficient decision tree, warns when it isn't exhaustive, and errors on unreachable cases. I use patterns for closed sets of data shapes and polymorphism when new types keep being added.

πŸ›  Real-world problems: how you handle them

Cancelled orders still shipped because two requests raced
Situation
Order service for [retailer] with web, mobile and warehouse integrations, [~12,000] orders a day. Three endpoints changed `Status` directly; the warehouse integration polled for Paid orders.
Signals
Customer complaints about receiving cancelled orders; refund team reporting [~40] a week at peak; warehouse logs showing pick lists for orders whose status was later Cancelled; no exceptions anywhere.
Investigation
Queried SQL Server temporal history on the Orders table to see status sequences per order; found Paid → Cancelled → Shipped within seconds. Application Insights end-to-end traces showed a customer cancel and a warehouse ship request on the same order milliseconds apart, both reading Paid.
Resolution
Immediate: the warehouse ship endpoint re-read the status inside a transaction with `UPDLOCK` as a stop-gap. Real fix: moved all transitions into the `Order` aggregate with a switch-expression table, made `Status` private-set, added a `rowversion` concurrency token, and mapped invalid transitions and concurrency failures to 409. The warehouse client retries after reloading.
Prevention
Table-driven transition tests in CI; an analyser rule banning direct `Status` assignment outside the aggregate; a dashboard of `DbUpdateConcurrencyException` counts and 409 responses; a nightly query alerting on any order history with Cancelled followed by Shipped.

How to tell it (STAR)

**S:** At [company], about [40] cancelled orders a week were still being shipped, and nobody could see an error. **T:** I needed to find out how and make it impossible. **A:** Using temporal-table history and Application Insights traces, I found cancel and ship requests racing on the same order, with three endpoints writing `Status` directly. I moved every transition into the order aggregate behind a switch-expression transition table, made the status private, added a `rowversion` token, and returned 409 for invalid or racing transitions. **R:** Shipped-after-cancel incidents dropped to [zero] within [a week], the concurrency check caught about [15] races a week that now resolve cleanly, and refund handling for that cause disappeared.

↩ Usually asked after

More in Behavioral Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me