Capstone — Decide Whether Checkout Can Launch
A checkout passes its peak-load test, but rollback strands a confirmed order. Use the failure budget and the clerk’s pickup queue to make the launch decision.
Beginner · Lesson 1 of 12
Software Architecture
One receipt covers two notebooks and a pen. Build three PostgreSQL tables and see why counting customers, orders, lines and physical pieces gives different answers.

Mariam puts two blue notebooks and one yellow pen on the counter. The notebooks cost AED 13.50 each and the pen costs AED 3.50. The shop prints one receipt for AED 30.50. At closing time the owner wants to know how many purchases Mariam made. The clerk wants to know how many pieces to put in her bag. If the database answers both questions by counting the same rows, at least one answer will be wrong.
Put the receipt beside the keyboard. You can find one customer, one purchase, two lines and three physical pieces on it. The numbers differ because each describes something different. In this lesson we will build three small PostgreSQL tables, enter that receipt, then read it back. By the end you should be able to predict which rows a second purchase adds, and what the database will do if a clerk tries to attach a line to an order that does not exist.
A row in customers represents one registered customer. A row in orders represents one purchase placed by one customer at a particular time. A row in order_lines represents one numbered entry on one purchase. Say those sentences before naming columns. The time of purchase belongs to the order because the whole receipt has one time. Quantity belongs to the line because a customer can buy two notebooks and one pen on the same visit. The customer's current display name belongs to the customer because she can make several purchases.
Consider the alternative of one spreadsheet row per receipt with columns for the first item and second item. It fits this sale exactly. On the next sale a third item needs another group of columns, and the shop's rule about prices must now apply in three places. One row per line accommodates a third item by adding a row. Copying every customer detail into those rows would introduce a different problem: correcting one customer's current name would require finding every copy. Separating the tables lets each fact have a clear home.
| Table | What identifies one row? | What can repeat? |
|---|---|---|
| customers | customer_id | A name can belong to several people |
| orders | order_id | A customer can place several orders |
| order_lines | order_id together with line_no | Different orders can each have line 1 |
Give Mariam customer ID 52 and her purchase order ID 481. The numbers are deliberately ordinary. Customer 52 remains the same customer if she changes the spelling of her name, and two customers called Mariam can have separate accounts. A primary key identifies a row uniquely and requires a value. It does not automatically identify who is allowed to view that row. Here we assign the numbers ourselves to make the example repeatable. A real till could have the database generate them while keeping the same relationships.
Order 481 carries customer_id 52 as a foreign key. That says the customer must exist. It does not say that customer 52 is limited to one order. Putting a unique constraint on the orders.customer_id column would accidentally prohibit her second purchase. In the opposite direction, a registered customer can exist before buying anything. There is no need to invent an empty order to give a new customer somewhere to belong. The direction of the reference expresses which row depends on which.
Use a two-column primary key for the lines. The pair (481, 1) identifies the notebooks and (481, 2) the pen. Order 482 can have its own line 1. A unique line number across the entire shop would force every receipt to continue numbering where the previous one left off. A product name also makes a poor line key: sometimes the same item appears twice on a receipt at different agreed prices. PostgreSQL documents both composite keys and the constraints that keep references valid. PostgreSQL constraints
In a fresh PostgreSQL practice database, create the tables in the order below. The customers table comes first because orders refers to it. The two columns of the order_lines primary key are implicitly non-null. The other mandatory fields say NOT NULL explicitly. Read the checks as statements about one row: a line number is positive, a sold quantity is positive, and a unit price may be zero for a free item but cannot be negative.
CREATE TABLE customers (
customer_id bigint PRIMARY KEY,
display_name text NOT NULL
);
CREATE TABLE orders (
order_id bigint PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers (customer_id),
placed_at timestamptz NOT NULL
);
CREATE TABLE order_lines (
order_id bigint REFERENCES orders (order_id),
line_no integer CHECK (line_no > 0),
item_label text NOT NULL,
quantity integer NOT NULL CHECK (quantity > 0),
unit_fils integer NOT NULL CHECK (unit_fils >= 0),
PRIMARY KEY (order_id, line_no)
);
The shop sells whole stationery items and charges only in dirhams. We record the price in fils, one hundred to the dirham. The integer 1350 therefore means AED 13.50. Writing the unit in the column name helps prevent someone from entering 13 and treating it as thirteen dirhams. An exact decimal column is another reasonable choice when the team wants to store dirham amounts directly. A floating-point approximation is a poor fit for a rule that must reconcile to the last fils. PostgreSQL numeric types
The item label and unit price are copies of what the customer actually bought. If blue notebooks go up to AED 15 tomorrow, today's line must still explain today's total. Later you could add a products table for current catalog facts and reference it from each line. That would answer which catalog product was sold. You would still need the charged price to answer what the buyer owed. For this first schema, keeping a label and a price snapshot is enough to reproduce the purchase details.
Insert Mariam first. Then save the order and its lines as one transaction. BEGIN starts the group and COMMIT accepts the changes together. If the pen line is invalid, roll back the failed transaction and correct the input before trying the sale again. The previously registered customer can remain. She exists independently of whether this particular purchase succeeds. PostgreSQL transaction tutorial
INSERT INTO customers (customer_id, display_name)
VALUES (52, 'Mariam');
BEGIN;
INSERT INTO orders (order_id, customer_id, placed_at)
VALUES (481, 52, '2026-11-30 10:15:00+04');
INSERT INTO order_lines
(order_id, line_no, item_label, quantity, unit_fils)
VALUES
(481, 1, 'Blue notebook', 2, 1350),
(481, 2, 'Yellow pen', 1, 350);
COMMIT;
The database now contains one customer, one order and two lines. There are three pieces in the bag because the quantities add up to three. The notebook line contributes 2 times 1350, or 2700 fils. The pen contributes 350 fils. Together they make 3050 fils. We have assumed no tax adjustment, discount or delivery charge. There is no stored total column to update separately when entering the receipt. The total here follows exactly from the two recorded lines.
The transaction groups writes, and the foreign keys require the referenced rows to exist. Neither feature, by itself, ensures that every order has at least one line. You could insert an order header and commit it without adding any lines. If this shop accepts only nonempty purchases, its checkout operation must reject an empty basket and commit the header only after it has saved the intended lines. That is a useful distinction when explaining what evidence a successful database write gives the clerk.
Use the matching keys to connect the three tables. In the query below, the short names c, o and l refer to customers, orders and order_lines. Each JOIN specifies the values that must match. ORDER BY asks for the printed line order explicitly. The multiplication uses a wider integer before multiplying so the result is not limited to the smaller range of a single integer column. PostgreSQL tutorial on joins
SELECT c.display_name, o.order_id, l.line_no, l.item_label,
l.quantity, l.unit_fils,
l.quantity::bigint * l.unit_fils AS line_fils
FROM orders AS o
JOIN customers AS c ON c.customer_id = o.customer_id
JOIN order_lines AS l ON l.order_id = o.order_id
WHERE o.order_id = 481
ORDER BY l.line_no;
Expect two result rows. Both contain Mariam and order 481. The first contains the notebooks and 2700 line fils. The second contains the pen and 350 line fils. The repeated name in this result is harmless: the query is presenting one row per line. It did not insert a second customer or record a second purchase. To count purchases by this customer, count her rows in orders. To count units sold, add quantities from the relevant lines. Before trusting a number, ask what one row of its input represents.
Test the rules with three separate attempts in a disposable copy. Insert another line numbered 1 on order 481 and the primary key rejects it. Insert line 1 for order 999, which has no header, and the foreign key rejects it. Insert line 3 on order 481 with a quantity of zero and the quantity check rejects it. Change just one thing in each attempt so you can tell which rule caught the problem. If you use explicit transactions, roll back each failed attempt before starting the next.
Notice a tradeoff in the printed receipt. Our query joins to the customer's current display name, so a later spelling correction changes the name on a reprint. That is useful for a current customer directory. If the shop promises an exact historical invoice, store the printed buyer name on the order as well, clearly labeled as a snapshot. It is possible to have good reason for recording two names once you can explain their different meanings and when each is allowed to change.
Mariam returns and buys three yellow pens at AED 3.50 each. Assign order 482 and start the line numbering at 1. Predict the number of rows in each table after both purchases, the number of physical items sold across the two visits, and the amount of the second receipt. Would an attempt to use line number 1 be valid?
Answer. Reuse customer 52, insert one new order referencing her, and insert the line (482, 1) with quantity 3 and unit_fils 350. There is still one customer. There are now two orders and three lines, covering six pieces. The second receipt is 1050 fils, or AED 10.50. Line 1 is valid because its order ID is part of the key. You have modeled the shop successfully when both receipts can be reconstructed independently and neither a duplicate line on the same receipt nor a line for a nonexistent order can be saved.
YOUR TAKE
Choose one reaction for this article.
A cookie helps limit repeat responses. Your feedback is private.