All lessons Leer en español

Security in depth · Unit 20 · Lesson 16 of 27

Business logic: valid steps, invalid outcomes

Reason about money, workflow state, repeated requests, and the rules a business must preserve.

11 minready

Helpful before thisWeb applications

After this lesson you can

  • write a business invariant
  • distinguish valid input from a valid state transition
  • explain idempotency and atomicity

A payment request times out, so the customer taps again. Should the shop charge twice? Every field can be well formed while the resulting behavior is still wrong.

Business invariant: A rule that must remain true across the states and transitions of a workflow.

Check current state → Apply one valid transition → Preserve the invariant1Check current state2Apply one validtransition3Preserve the invariant
A safe workflow validates the transition and preserves the business rule, including during retries.

Start with a rule that must stay true

An invariant is a condition the system must preserve. A refund cannot exceed the amount actually paid. A gift card balance cannot become negative. An order cannot be shipped before the required payment state exists. These rules depend on business meaning, so a generic input validator cannot discover them for you.

Write the rule with the people who own the process. Clarify currencies, rounding, cancellation windows, and exceptional cases. Ambiguity becomes an implementation decision, whether anyone notices or not.

State lives on the server

A workflow has states and permitted transitions. The server should determine the current state and the authoritative amounts, rather than trust a screen’s hidden field or a client’s statement that a previous step happened. Authorization applies to the transition as well as the object.

Distributed systems also receive duplicate messages, delayed responses, and out-of-order events. A robust design anticipates those ordinary conditions instead of treating every repeat as a new instruction.

Retries and concurrency change the problem

Idempotency means repeating an operation has the intended equivalent effect of one operation within its defined semantics. An idempotency key must be scoped and bound to the appropriate request; it is not permission to perform that request.

Atomic operations or transactions can keep a check and update consistent when requests overlap. A workflow may need reconciliation when an external payment provider and an internal order database disagree. Logs should connect the business operation across retries without exposing payment secrets.

Work from a ledger, not from a reassuring screen

A fictional library has one remaining place in a workshop. Its policy says held places plus confirmed places cannot exceed capacity. A temporary hold reserves a place until its stated expiry; confirmation converts that same hold into a booking. It must not count as a second place. Cancellation releases a place only if an active hold or booking actually existed.

Supplied transition Required decision State that must remain true
Current hold becomes confirmed Permit for its authorized holder One occupied place remains one
Confirmation arrives after hold expiry Re-evaluate availability and permission Expired state does not promise a place
Confirmed booking is cancelled twice Record one cancellation effect The second delivery adds no extra capacity
Two people request the last place Resolve competing claims consistently At most one obtains that place

These rules need an agreed time source and a precise meaning of expiry. If confirmation and expiry occur close together, the design must determine which state transition wins. A message arriving later does not necessarily describe a later event. The booking record’s authoritative state, not the order in which screens update, decides what is currently possible.

Separate a repeated intention from a new intention

An idempotency mechanism records enough information to recognize the same intended operation. Its scope might include the account, operation type, and agreed request details. Reusing the same operation reference with different details must have a defined result, rather than silently borrowing a previous success. Define how long the reference remains useful and what a legitimate retry sees after that period.

Idempotency concerns the intended effect, not a guarantee of identical response text or zero repeated logging. It also does not mean every method or product automatically supports safe retries. For this library, two deliveries of the same cancellation release one place; two genuinely different reservations are evaluated as separate requests against the capacity rule.

PredictThe supplied booking record already says “cancelled.” A duplicate cancellation message arrives. Should the service increase available capacity again because this is a new message?

No. The message is another delivery, but there is no remaining occupied place to release. Returning the established cancellation result is reasonable under this policy. Creating a new booking would need its own authorized intention and availability decision; treating all repeats as errors could also confuse a legitimate retry.

Ask what the transaction actually covers

A transaction groups changes, but correct concurrency behavior still depends on its isolation and the conditions enforced within it. Merely surrounding separate availability checks with a transaction does not prove that competing reservations preserve capacity. The review needs evidence that the chosen design resolves overlapping changes without granting the same last place twice.

An external confirmation service may remain outside that database transaction. If its response is missing, record an unresolved state and reconcile with trustworthy operation evidence. Avoid guessing either success or failure just to simplify the interface. The learner’s review deliverable should name the invariant, the ambiguous transition, the authority that resolves it, and the evidence needed before calling the booking confirmed.

EXPLORE THE CONCEPT

One purchase, three timelines

Explore normal reliability events that a secure checkout must handle.

The customer retries

Recognize the same intended payment and return its established result where appropriate; do not blindly create another charge.

Two updates overlap

Preserve the balance rule with a suitable atomic operation or transaction. Two separate checks may see the same old state.

The provider succeeds but the app times out

Reconcile using trustworthy operation status. A timeout is uncertainty, not proof that the payment failed.

A simplified learning model. It connects to no systems and uses no real data.

Turn the idea into a decision

Security includes keeping promises about money and state. Test the invariant through retries and failures, not only the happy path.

Terms you met

Business invariant

Check yourself

No timer. No penalties. Read the explanation and try again whenever you like.

  1. The workshop has ten places. Which review statement expresses the relevant invariant?

    Show the answer

    Correct answer: Held plus confirmed places never exceed ten. This relates changing state to a business condition that must remain true.

  2. A payment provider’s result is missing after a timeout. Which state is justified by that evidence alone?

    Show the answer

    Correct answer: Unresolved, requiring reconciliation with the operation’s trustworthy status. The timeout leaves uncertainty about the remote result.

  3. A caller repeats a known operation reference after losing permission for its protected result. What should the design establish?

    Show the answer

    Correct answer: Authorization for disclosure as well as the defined duplicate-operation behavior. Recognizing the intended operation does not itself grant access to its protected result.

  4. Two reservations overlap for one remaining place. Which review evidence addresses the actual failure mode?

    Show the answer

    Correct answer: The chosen state-change mechanism admits at most one booking and preserves capacity. This checks the invariant under competing operations.

Try it

  • WriteWrite three invariants for a fictional library reservation system, including what happens when the same reservation is submitted twice.
References