Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 40 ยท Practice and Review

Practice Exercises with Solutions

Six runnable e-commerce exercises with worked solutions: splitting cents, stacking discounts, tax rounding, stock holds, order states and webhook signatures.

The bugs that cost online shops money are rarely exotic. They are a cent that vanishes when a total is split, a discount applied in the wrong order, a tax figure that differs by one cent between two screens, a stock count that goes negative, an order that jumps to a status it should never reach, or a webhook that anyone can forge. This lesson gives you one small exercise for each of those, with a solution you can run and change.

Work in this order for each exercise: read the task, write your own version in the editor (clear the solution first, or copy it somewhere), run it, then compare. Every solution ends with assertions, so a wrong answer fails loudly instead of quietly printing a plausible number. If your approach differs from the solution but passes the assertions, think about which one you would rather maintain.

flowchart LR
  E1["1. Split cents"] --> E2["2. Stack discounts"]
  E2 --> E3["3. Round tax"]
  E3 --> E4["4. Hold stock"]
  E4 --> E5["5. Order states"]
  E5 --> E6["6. Verify signatures"]

Money first, then stock, then states, then trust at the edge.

All amounts are integers in minor units (cents) unless an exercise says otherwise. If that feels unfamiliar, read Representing Money Correctly first. The Python exercises run in the browser, and the signature exercise runs on the server-side Node runner.

Exercise 1: split an amount without losing a cent

Task. A $10.00 order discount must be spread across three line items in proportion to their prices (2500, 1500 and 1000 cents), and a $10.00 shipping fee must be split evenly between three packages. Write allocate(total, weights) that returns one integer per weight, always adds up to total exactly, and gives leftover cents to the parts with the largest fractional remainders (ties go to the earlier part).

Why it matters. round(1000 / 3) three times gives 333 + 333 + 333 = 999. One cent is missing, and refunds, tax reports and accounting exports will disagree about it forever. This is the same allocation idea used for proration in Building a Promotions Engine.

Hint. Take the floor of each exact share first. The leftover is smaller than the number of parts, so hand out one cent at a time.

Python Exercise 1: allocate cents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A discount that is allocated this way can be refunded later line by line: the returned amounts always add back up to the original discount.

Exercise 2: stack discounts in a defined order

Task. A cart subtotal is 10,000 cents. A customer has a 20% coupon and a $10.00 (1000 cents) gift offer. Write apply_discounts(subtotal, steps) that applies a list of ("percent", n) or ("fixed", cents) steps in order, rounds percentages half up to a whole cent, and never lets the total go below zero. Show that the order of steps changes the result, then decide which order your shop uses.

Why it matters. "20% off and $10 off" is ambiguous. Percent first gives 7000, fixed first gives 7200. Neither is wrong, but the shop must choose one, write it down and apply it identically on the cart page, in the order and in the invoice.

Hint. For positive integers, half-up rounding of total * n / 100 is (total * n + 50) // 100, with no floats at all.

Python Exercise 2: discount order matters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Many shops apply percentage discounts first and fixed amounts last, because the customer then keeps the full value of a fixed gift card or voucher. Whatever you choose, make the rule explicit data (a priority number on each promotion), not an accident of loop order.

Exercise 3: tax per line or per invoice

Task. An order has three lines of 999 cents each and the tax rate is 8.25%. Calculate the tax two ways: rounding each line's tax, and rounding the tax on the whole invoice. Then take a tax-inclusive price of 999 cents with 20% VAT and split it into net and VAT. Use Decimal and round half up.

Why it matters. The two methods can differ by a cent, and both can be legal in different places. Consistency is the real requirement: the same method on screen, in the confirmation email and in the accounting export. See Sales Tax, VAT and GST for where each method applies, and Decimal and Fractions for the tool.

Hint. For a tax-inclusive price, the net is gross / (1 + rate). Round the net, then define the tax as gross - net, so the two parts always add up to what the customer paid.

Python Exercise 3: rounding tax

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The invoice method gives 247 and the line method 246. Neither is a bug in the code, but a shop that shows one number in the cart and another on the invoice has a support ticket waiting to happen.

Exercise 4: available stock with expiring holds

Task. A product has 10 units on hand. Customers place holds (reservations) that expire at a given time. Write available(on_hand, holds, now), which ignores expired holds, and try_hold(...), which adds a hold only if enough stock is available. Simulate: hold 4 until time 100, hold 5 until time 50, try to hold 3 more at time 10 (should fail), then try again at time 60 (should work because the second hold has expired).

Why it matters. This is the core of Reservations and Overselling: stock is not a single number but the difference between what you have and what is promised. Forgetting to expire holds makes products look sold out when nobody is buying.

Hint. Keep holds as data and compute availability from them on demand. A stored counter that you increment and decrement by hand drifts when a code path forgets to undo it.

Python Exercise 4: holds with a time limit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real system the check and the insert must be one atomic step (a conditional update or a row lock). This single-threaded stand-in cannot show that race, which is why the inventory service project simulates concurrency.

Exercise 5: find the illegal order transition

Task. Define the allowed order transitions: pending goes to paid or cancelled; paid goes to fulfilled or refunded; fulfilled goes to refunded; cancelled and refunded are final. Write first_illegal(history) that returns the first illegal pair in a list of statuses, or None if the history is valid. Test it on four histories, including one that "un-cancels" an order.

Why it matters. Order statuses are the shop's memory. An audit of old orders using a function like this finds the bug that let an order go from cancelled back to paid. The full model lives in The Order Lifecycle and State Machines.

Python Exercise 5: validate a status history

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Note the last assertion: an unknown status is also an illegal transition, because ALLOWED.get(current, set()) treats a status it has never heard of as one with no exits.

Exercise 6: verify a webhook signature

Task. A payment provider sends the header t=<unix seconds>,v1=<hex hmac> and signs the string <t>.<raw body> with HMAC-SHA256 and a shared secret. Write verify(header, rawBody, secret, now, toleranceSeconds) that returns { ok: true } or { ok: false, reason }. It must reject malformed headers, timestamps outside the tolerance (replay protection), and wrong signatures, compare signatures in constant time, and accept any of several v1= values (providers send two while rotating secrets).

Why it matters. The webhook endpoint is public. Without verification, anyone can POST "payment succeeded" for any order. See Webhooks and Signature Verification.

Hint. Sign and verify the raw bytes you received, not a re-serialized copy of the parsed JSON. crypto.timingSafeEqual throws if the two buffers have different lengths, so check the length first.

Node.js Exercise 6: HMAC webhook verification

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A few details are worth a second look. The tolerance check happens before any signature work, so a flood of old replays is rejected cheaply. The signed string includes the timestamp, so an attacker cannot refresh an old request by changing only the t= value. And every failure returns a reason for your logs, but the HTTP response to the sender should be a plain 400 without those details.

Where to go next

If any solution surprised you, go back to the lesson behind it before you continue. For a longer practice session, rebuild a project from scratch without looking: the order engine exercises money, promotions, tax and states together, and the checkout API adds HTTP and idempotency.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Splitting 1000 cents into three equal parts with round() on each part gives 999 in total. What is the reliable fix?

    Flooring keeps every share an integer and the leftover is fewer cents than there are parts. Handing them out by remainder keeps the split fair and the sum exact.
  2. 2. A 20% coupon and a fixed $10 discount give different totals depending on order. What should a shop do?

    Both orders are valid business rules. The bug is inconsistency between the cart, the order and the invoice.
  3. 3. For a tax-inclusive price, why is the tax computed as gross minus the rounded net?

    Rounding net and tax separately can produce a total that is one cent off. Deriving one from the other guarantees the parts add up.
  4. 4. Why does verify() compare the signature with timingSafeEqual after checking the lengths?

    A normal comparison can stop at the first differing byte, which can leak information through timing. The function requires equal lengths, so the length check comes first.
  5. 5. Why is the timestamp part of the signed string in a webhook signature?

    If only the body were signed, a captured request could be replayed at any time. Signing the timestamp binds the signature to it and lets the receiver reject old requests.

Summary

  • Allocate money by flooring each share and giving leftover cents to the largest remainders; the parts must always add up to the total.
  • Discount order is a business rule: store it as data and apply it identically everywhere, and never let a total go below zero.
  • Choose one tax rounding method and use it consistently; derive tax from gross minus net for inclusive prices.
  • Compute available stock from on-hand quantity and active holds instead of maintaining a hand-edited counter.
  • Check order histories against an explicit transition table, and treat unknown statuses as illegal.
  • Verify webhooks on the raw body with a constant-time compare, a timestamp tolerance and support for several signatures.

Next: E-commerce Interview Questions