BM
Bashar ModallalSOFTWARE · AI · SYSTEMS
Backend Engineering

Intermediate · Lesson 4 of 12

Software Architecture

Validate Inputs and Business Rules

Follow one order cancellation through malformed JSON, an unsupported reason and a dispatch conflict. Design error responses and test the state change.

A shop clerk holds an amber slip above a sealed parcel beside a box of blue notebooks.

Maryam taps Cancel on a notebook order. The app highlights the reason field in red and asks her to try again. She picks a different reason. The same message appears. At the warehouse, the parcel is already on the courier’s van. Nothing Maryam types can make that parcel eligible for cancellation. The backend knew exactly why it rejected her request, but the error sent her looking for a mistake in the wrong place.

We will design this interaction for a stationery shop. One purchase, order 8144, is enough to expose three different problems: a message the server cannot read, a readable message with an unacceptable field, and a valid instruction that the shop can no longer carry out. By the end you should be able to predict the HTTP response, the database outcome and the next useful action on the phone for each case.

Write the shop’s promise before choosing a status code

Assume Maryam is signed in and owns order 8144. The shop allows a customer to cancel while an order is marked received. Once it is dispatched, she must use the returns process. The customer chooses one of two reasons, ordered_by_mistake or no_longer_needed. These values let the warehouse group cancellations without depending on the language of the interface. The server records the reason together with the change of state. This exercise leaves billing and refunds outside the operation.

The phone sends POST to /orders/8144/cancellations with a JSON body such as {"reason":"no_longer_needed"}. The client supplies no order status. A status displayed on a screen is a useful hint for showing or hiding a button, but the screen is a snapshot. We also specify what a second cancellation means: once the order has been cancelled, a new attempt receives a conflict and may read the existing confirmation. There is one successful transition and one audit entry. This is a deliberate choice for this API. A service promising replay of the first success would need a different documented contract.

Read the same operation in three passes

First ask whether the bytes describe a JSON value at all. A body ending immediately after the colon in {"reason": cannot be parsed. Return 400 in this contract, identify malformed JSON and stop before calling the order operation. There is no trustworthy reason field to highlight. If a customer using an unmodified mobile app sees this result, the likely corrective work belongs to the app team. Asking the customer to spell the reason differently misses the failure entirely.

Next ask whether the parsed value satisfies the request schema. An empty object, an array in place of an object, or a reason of "too_late" are all valid JSON. None describes a supported cancellation command. For these inputs the shop returns 422 with a field or document error as appropriate. For an unsupported reason, the phone can preserve the order number, reload the supported choices if necessary, and let the customer pick again. A text field should never silently turn an unknown value into the first available reason. That would put an explanation into the customer’s record that she did not give.

Finally ask whether the operation is possible for this customer and this order now. A correctly spelled supported reason stays correct when a courier picks up a parcel. The state transition becomes impossible. Return 409 for a conflict with the current order state, explain what changed, and let the customer refresh the order before choosing what to do next. These mappings are choices within the shop’s contract. The distinctions between malformed requests, unprocessable content and a conflict with a resource’s current state come from the HTTP specification. HTTP Semantics, RFC 9110

Observation Shop response Next action
Truncated JSON 400, malformed document Fix how the client serializes the message
Recognized document with an unknown reason 422, unsupported reason Select a supported value
Valid reason for an already dispatched order 409, order dispatched Refresh and show the returns option
Valid reason for a received order 200, cancelled order Show the saved cancellation confirmation

Follow order 8144 through two possible afternoons

At 14:01 Maryam reads the order. Its state is received and its version is 7. At 14:02 she submits a valid reason. On a quiet afternoon the order is still received. The service locates it within her account, records the transition and reason, appends one audit event and commits. The response contains order 8144, the state cancelled and version 8. A subsequent read from her account shows that same state. A useful acceptance test checks both the response and the durable event; a green confirmation on the phone alone would miss a write that never committed.

Now rewind to 14:01. This time the warehouse dispatches the parcel between Maryam opening the screen and sending her request. Dispatch commits first and advances the version to 8. Her phone submits the exact same bytes as on the quiet afternoon. Parsing succeeds. The reason passes validation. The cancellation makes no change, the stored state remains dispatched at version 8, and there is no cancellation event. The evidence that explains the different outcomes lives in the order history. Replaying just the HTTP body in a test that always starts with a newly received order will never reproduce the conflict.

Make the response useful to the person operating the app

For this conflict, return a problem document with an actual HTTP status of 409 and a content type of application/problem+json. In the example below the type identifies a stable category that the client understands, while the detail explains this case to the customer. The shop defines currentState and orderId as extensions. Return order-specific information only after establishing that the customer may see this order. A lookup outside the customer’s permitted orders follows the service’s visibility policy and discloses no shipment details. Problem Details for HTTP APIs, RFC 9457

{
  "type": "https://shop.example/problems/order-dispatched",
  "title": "This order has been dispatched",
  "status": 409,
  "detail": "Refresh the order to see return options.",
  "orderId": "8144",
  "currentState": "dispatched"
}

The Arabic interface can show a localized title and the same stable problem type. The mobile code branches on that type; it does not search inside an English sentence for the word dispatched. Reserve a different type for a request to cancel an already cancelled order. In that case the useful destination is the existing confirmation, and telling the user to arrange a return would be confusing. A generic client that does not know a new problem type can still display an appropriate message and offer to reload the order.

Put the final decision next to the write

Reading the status, checking it in application memory and then saving a new status leaves a gap. A dispatch can commit in that gap. Two individually reasonable operations can overwrite each other if each updates the row unconditionally. Let the database participate in the decision. The simplified PostgreSQL statement below changes the row only if it still belongs to the customer and is still received. The placeholders stand for bound parameters. Execute the statement and the audit insert in one transaction; publish success only after commit.

UPDATE orders
SET state = 'cancelled', cancel_reason = $1, version = version + 1
WHERE id = $2 AND customer_id = $3 AND state = 'received'
RETURNING id, state, version;

One returned row gives the service the values for the audit entry and response. Zero returned rows mean the condition did not match. That fact alone cannot tell you why. Read the visible order again before picking a problem type. A dispatched order, an already cancelled order and an absent order call for different explanations. Under PostgreSQL’s Read Committed isolation, a competing update to the same row can make the second updater wait and recheck its condition against the updated row. Make the dispatch path enforce its own allowed starting state too. A guarded cancellation cannot compensate for a warehouse job that blindly overwrites cancelled orders. PostgreSQL transaction isolation

Catching all database exceptions and turning them into 409 is another tempting shortcut. A failed database connection gives the service no evidence that the order was dispatched. A failure while inserting the audit event should roll back the state change. A lost connection while waiting for commit confirmation can leave the caller uncertain about the outcome. Report the appropriate service failure and reconcile the order before encouraging another submission. The conflict response makes a precise claim about the business record; send it only when the service has evidence for that claim.

Test the difference a customer can observe

Set up three fresh copies of the same order in isolated test cases. For malformed JSON, assert that no order operation ran. For an unsupported reason, assert the 422 response identifies the reason and that the state and event count are unchanged. For a dispatched order, keep the body valid and assert the conflict type, version and absence of a cancellation event. Finally perform the happy path and check that the recorded reason matches what Maryam selected. These assertions catch errors that a test looking only at a status code would overlook.

For a concurrency test, use two database connections and control when each transaction proceeds. Let dispatch update the row and hold its transaction open. Start the conditional cancellation on the second connection, then commit dispatch. The cancellation must not produce a second successful transition. Reverse the order in a fresh fixture and require the warehouse to respect cancellation. Using an explicit synchronization point makes the test repeatable; two arbitrary sleeps can make the same broken implementation pass on a slow machine and fail on a fast one.

اقرأ الدرس بالعربية

Exercise: give support a decision it can defend

A customer reports that cancellation failed. The body contains a supported reason. The initial order read shows received at version 7. The database update returned zero rows and the latest permitted read shows dispatched at version 8. Write the response status, the next action for the customer, and the number of cancellation audit events this attempt should add. Then change only the input to a truncated JSON document. Which observations should the service still need?

Answer. Return 409 with the dispatched-order problem type, suggest refreshing the order to see return options, and add zero cancellation events. With truncated JSON, return 400 and explain that the message could not be decoded. No order-state read or attempted transition is needed to make that determination. If a proposed fix tells both customers to edit their reason, it has collapsed two failures with different causes into one unhelpful instruction.

YOUR TAKE

What did you think?

Choose one reaction for this article.

Was this useful?

A cookie helps limit repeat responses. Your feedback is private.

Share this noteLinkedIn ↗X ↗Email ↗

Keep exploring.

Software Architecture9 min read

Design Your First Resource API

Design and test an order API that creates a purchase, retrieves its original receipt and tells a shopper exactly how to fix an invalid quantity.

Read article ↗

Software Architecture10 min read

Follow an HTTP Request

Trace a two-notebook purchase from DNS and TLS to a committed order, and learn what a checkout timeout can actually prove.

Read article ↗