State machines and optimistic locking
You can model role-authorized transitions and reject stale order writes, giving the next exercise a precise lifecycle and concurrency contract.
Learning outcomes
- Model the order lifecycle as a state machine with explicit statuses, event types, roles and allowed transitions.
- Distinguish forbidden events from illegal transitions and enforce order visibility before event authorization.
- Explain how optimistic locking prevents two requests from applying a transition based on the same order version.
- Handle event ID replays without applying a transition twice.
- Keep the order update, event history and outbox row consistent through a database transaction.
An order starts as PLACED. A restaurant can accept or reject it, a customer can cancel it, and a rider can eventually deliver it. Each action must be valid for the current status and the caller's role. You also need to handle two restaurant users accepting the same order at almost the same time without applying the transition twice.
The order already has a status and a version in MySQL. The exercise adds rules around those fields and uses them to protect every transition. The same API also needs to return an order's history and list the caller's orders.
The order lifecycle
A state machine describes which states an order can occupy and which events can move it between them. For this API, each transition also has an allowed role.
A status describes the order's current position. An event type describes the action a caller wants to perform. The allowed role determines who can request that action.
| From | Event type | To | Allowed role |
|---|---|---|---|
PLACED | ACCEPT | ACCEPTED | restaurant |
PLACED | REJECT | REJECTED | restaurant |
PLACED | CANCEL | CANCELLED | customer |
ACCEPTED | START_PREP | PREPARING | restaurant |
ACCEPTED | CANCEL | CANCELLED | customer |
PREPARING | MARK_READY | READY | restaurant |
READY | PICK_UP | PICKED_UP | rider |
PICKED_UP | DELIVER | DELIVERED | rider |
This table is the lifecycle contract. An event is valid only when both the current status and the event type match a row, and the caller has the role specified by that row.


Three statuses are terminal: REJECTED, CANCELLED and DELIVERED. Nothing leaves these states. For example, a restaurant cannot accept an order after rejecting it, and a rider cannot deliver an order that has already been cancelled.
The frontend can hide buttons that do not apply to the current status. That is useful for the customer experience, but it does not enforce the lifecycle. A caller can send an HTTP request directly, and the server must validate every event.
Lifecycle rules as data
Keep the lifecycle rules together instead of scattering them across HTTP handlers. This makes the allowed transitions visible and gives you one consistent place to validate them.
Go's named types make the different values distinct:
type Status string
type Event string
type Role string
const (
Placed Status = "PLACED"
Accepted Status = "ACCEPTED"
Preparing Status = "PREPARING"
Ready Status = "READY"
)You can represent a transition using the current status and event type as its key. Its value is the next status.
type transition struct {
from Status
event Event
}
var next = map[transition]Status{
{Placed, "ACCEPT"}: Accepted,
{Accepted, "START_PREP"}: Preparing,
}This is a partial example of the lifecycle data. The complete table also includes rejection, cancellation, preparation completion, pickup and delivery.
The allowed role is a separate rule. For example, ACCEPT belongs to restaurant accounts, while PICK_UP belongs to rider accounts. Separating the two rules matters because they answer different questions:
- The transition table answers whether an event is valid from the current status.
- The role rule answers whether the caller may perform that event.
A single status check cannot answer both questions correctly.
Authorization and visibility
The order API has two distinct access checks. First, you decide whether the caller may see the order. Then you decide whether the caller's role may perform the requested event.
A customer sees their own orders. A restaurant user sees orders belonging to their restaurant. A rider can see any order.
The caller comes from the authentication middleware, which placed the authenticated principal in the request context. The order's customer and restaurant ownership come from MySQL.
An inaccessible order returns 404 order_not_found, the same response as a nonexistent order. Returning 403 would reveal that the order ID exists, even though the caller cannot access it.
After visibility is established, check the event's role before checking whether the current status allows the event.
Consider a customer sending ACCEPT for an order in PLACED status. The customer is not allowed to accept orders. The API returns 403 forbidden.
Now consider a restaurant user sending DELIVER while the order is still PLACED. The restaurant role is not allowed to perform DELIVER, so this also returns 403 forbidden. It does not matter that DELIVER is also invalid from PLACED.
A different result applies when the role is correct but the transition is not. A rider sending PICK_UP while the order is PLACED receives 409 illegal_transition.
The distinction is important:
| Condition | Response |
|---|---|
| The caller cannot see the order | 404 order_not_found |
| The caller can see it but cannot perform the event | 403 forbidden |
| The caller's role is permitted, but the status does not allow the event | 409 illegal_transition |
The server uses this order of checks to avoid exposing lifecycle information to callers who are not permitted to perform an event.
The lost update
Concurrency creates another problem. Imagine two employees of the same restaurant open an order at the same time.
Both read an order with status PLACED and version 1. Both decide that ACCEPT is valid. Both then try to change the status to ACCEPTED.
A naive implementation might issue this SQL:
UPDATE orders
SET status = 'ACCEPTED'
WHERE id = ?;This statement does not check whether another request has already changed the order. Both requests can update the same row, even though only one should have applied the transition.
This is a lost-update problem. The application validated an earlier version of the order, but its update did not verify that the version was still current.
Optimistic locking
Optimistic locking handles this problem by assuming that concurrent changes are uncommon. Instead of locking the order before reading it, you read its current version and require that version to remain unchanged when you write.
The orders.version column acts as a concurrency token. Every successfully applied transition increases it by exactly one.
The update includes the status and version that the request originally read:
UPDATE orders
SET status = ?, version = version + 1
WHERE id = ? AND status = ? AND version = ?;This is a compare-and-set operation. MySQL changes the row only if all the conditions still match.
Suppose both requests read version 1. The first request updates the order and commits version 2. The second request still expects version 1, so its update affects zero rows.
Go can inspect the result of an SQL update:
result, err := tx.ExecContext(ctx, query, args...)
if err != nil {
return err
}
affected, err := result.RowsAffected()
if err != nil {
return err
}An affected-row count of zero means your expected version was no longer current. You must not continue by recording an event for a transition that did not update the order.
The version check is what prevents both requests from applying the same transition. Checking only the status is weaker because a row can change and later return to an earlier status. A monotonically increasing version records that a change happened even when the status value alone would not reveal it.
Competing transitions
A failed conditional update does not always mean the same thing as an invalid transition.
The second restaurant request in the previous example initially saw PLACED. Another request changed the order to ACCEPTED first. The losing request can read the current order again and evaluate its event against the new status.
ACCEPT is not allowed from ACCEPTED. The second request can therefore return 409 illegal_transition after re-evaluating the lifecycle rules.
Alternatively, an implementation can report 409 concurrent_update when it detects that another request won the race.
Both responses represent a conflict. The important property is that exactly one request returns 200 and the order version increases exactly once.


Do not keep retrying indefinitely. A retry must start from a fresh read, and the transition must be validated again. Retrying a stale update with the same old version can never make it valid.
Event IDs and replay
A status check alone cannot handle a client retry correctly. Consider a restaurant that sends ACCEPT, but the HTTP response never reaches its device.
The transition may have committed successfully. When the client retries, the order is already ACCEPTED. Evaluating ACCEPT against that status would produce 409 illegal_transition, even though the client is repeating an action that already succeeded.
The request therefore carries an event_id. The database records this ID with the applied order event.
Before attempting a new transition, the application checks whether the event ID already exists.
There are two different outcomes:
- If the ID belongs to the same order, the request is a replay. Return the current order with 200, without applying another transition or increasing the version.
- If the ID belongs to another order, reject the request with 409 and error
event_id_conflict.
This means the event ID identifies an already-applied action, not merely a particular status. The same event ID cannot be used to advance two different orders.
A unique database constraint on order_events.event_id is important. Checking for an existing ID before inserting is useful, but two requests can perform that check at the same time. The unique constraint protects the database when both attempt to insert the same ID.
MySQL reports a uniqueness violation as a duplicate-key error. In Go, you can inspect the underlying MySQL error and distinguish that case from other database failures.
var mysqlErr *mysql.MySQLError
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
// A unique key was violated.
}A duplicate-key error does not by itself tell you whether the ID belongs to the same order or another order. Check the existing record's order_id to determine whether the request is a replay or an ID conflict.
Atomic transitions
An order transition changes more than one database record. It changes the current order, creates an order event for the history, and creates an outbox row for later publication.
These writes must be atomic. A database transaction gives you that guarantee.
Consider the three records involved in accepting an order:
ordersstores the new status and version.order_eventsstores the transition and the actor.outboxstores the event that the relay must publish later.
If the status update succeeds but the event insert fails, the order has changed without a corresponding history record. If the event insert succeeds but the outbox insert fails, downstream services have no durable record to publish.
A transaction makes these changes one unit. Either all of them commit, or none of them do.
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
// Perform the related database writes using tx.
if err := tx.Commit(); err != nil {
return err
}The example shows transaction ownership, not the complete transition implementation. Every database write belonging to the transition must use the transaction rather than the original sql.DB.
The conditional order update belongs inside that transaction, followed by the event and outbox inserts. If any write fails, the transaction must roll back. That also means a rejected transition must not leave an outbox row behind.
The API does not publish directly to Kafka while handling the HTTP request. The outbox row is durable database state. W3B6 adds a relay that reads those rows and publishes them to order-events, keyed by order ID.
This separation matters because committing a MySQL transaction and publishing a Kafka message are not one atomic operation. The outbox preserves the event until the relay can publish it.
Order history and reads
The current status tells you where an order is now. Its event history explains how it reached that status.
For an order that has reached READY, the history must include the initial placement and every transition:
| From status | To status |
|---|---|
| empty | PLACED |
PLACED | ACCEPTED |
ACCEPTED | PREPARING |
PREPARING | READY |
The initial placement is an order event too. Omitting it would leave the history without a record of how the order entered the lifecycle.
Order detail returns the events oldest first. This gives the caller a chronological account of the order. The order list serves a different purpose: it returns the caller's orders newest first, without embedding their event histories in every list item.
The list uses cursor pagination. A stable ordering lets the client fetch the next page without repeating orders. In this API, the page is scoped to the authenticated caller, and following next_cursor must not expose another customer's orders.
Both read endpoints still need the same visibility rules. A rider can read any order, but a customer cannot use the order list or detail endpoint to access another customer's records.
The order lifecycle exercise
The order lifecycle exercise brings these ideas together in POST /v1/orders/{id}/events, GET /v1/orders and GET /v1/orders/{id}.
The transition rules define which changes the API permits. The caller's role and ownership determine which requests are allowed. Optimistic locking protects updates based on an old version, while event IDs make retries safe.
The database must retain the complete event history and an outbox row for every applied transition. These writes belong in the same transaction, so the relay in the next step receives only committed order events.
The exercise also checks that order detail returns events oldest first and that the caller's order list uses newest-first cursor pagination. Keep the lifecycle rules independent of the persistence details so you can reason about each failure separately.
Check your understanding
Two restaurant users send ACCEPT for the same order. Both initially read status PLACED and version 1. Why must one request fail?
References
Everything above is explained on this page; these are where it comes from (Go 1.25, MySQL 8.4 InnoDB).