Domain design and the schema
Get this chapter right and the rest of the project is mechanical. Get it wrong and you will be writing defensive code in three layers to compensate for a schema that permits nonsense.
The aggregate
An order and its lines change together and must be consistent together — one total, one status, one version. They are a single aggregate with one entry point. Customers and products are referenced by id but live in their own aggregates.
If two things must be correct at the same instant, they belong in one aggregate and one transaction. If eventual consistency is acceptable, they do not. Order total and order lines: same aggregate. Order and customer's lifetime spend: not.
Invariants
| Rule | Enforced by |
|---|---|
| Total equals the sum of its lines | Service, recalculated on every mutation |
| Total is never negative | CHECK constraint |
| Quantity is at least 1 | CHECK constraint |
| A product appears at most once per order | UNIQUE (order_id, product_id) |
| A placed order has a placement time | Table-level CHECK |
| Only legal state transitions | Service state machine + WHERE status IN (…) |
| Two operators cannot both edit | version column, optimistic locking |
| Every transition is auditable | order_event, written in the same transaction |
Note how many of these are database constraints. A rule enforced only in Java is a rule a background job, a data fix or a second service will eventually break.
The schema
CREATE EXTENSION IF NOT EXISTS citext;
CREATE TYPE order_status AS ENUM
('DRAFT','PLACED','PAID','FULFILLED','DELIVERED','CANCELLED','REFUNDED');
CREATE TABLE customer (
customer_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email citext NOT NULL UNIQUE,
full_name text NOT NULL CHECK (length(trim(full_name)) > 0),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE product (
product_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
sku text NOT NULL UNIQUE,
name text NOT NULL,
price numeric(12,2) NOT NULL CHECK (price >= 0),
stock_qty integer NOT NULL DEFAULT 0 CHECK (stock_qty >= 0)
);
CREATE TABLE customer_order (
order_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customer ON DELETE RESTRICT,
reference text NOT NULL UNIQUE,
status order_status NOT NULL DEFAULT 'DRAFT',
total_amount numeric(12,2) NOT NULL DEFAULT 0 CHECK (total_amount >= 0),
currency char(3) NOT NULL DEFAULT 'EUR',
metadata jsonb NOT NULL DEFAULT '{}',
version integer NOT NULL DEFAULT 0,
placed_at timestamptz,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT placed_at_consistent CHECK (
(status = 'DRAFT' AND placed_at IS NULL) OR
(status <> 'DRAFT' AND placed_at IS NOT NULL)
)
);
CREATE TABLE order_line (
line_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id bigint NOT NULL REFERENCES customer_order ON DELETE CASCADE,
product_id bigint NOT NULL REFERENCES product ON DELETE RESTRICT,
quantity integer NOT NULL CHECK (quantity > 0),
unit_price numeric(12,2) NOT NULL CHECK (unit_price >= 0),
line_total numeric(12,2) GENERATED ALWAYS AS (quantity * unit_price) STORED,
UNIQUE (order_id, product_id)
);
-- append-only audit of every state change
CREATE TABLE order_event (
event_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
order_id bigint NOT NULL REFERENCES customer_order ON DELETE CASCADE,
from_status order_status,
to_status order_status NOT NULL,
actor text NOT NULL,
note text,
occurred_at timestamptz NOT NULL DEFAULT now()
);
-- transactional outbox: published by a poller, never by the request thread
CREATE TABLE outbox_event (
event_id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
aggregate_id bigint NOT NULL,
type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
Indexes, chosen for the actual queries
-- the list screen: filter by customer, newest first
CREATE INDEX idx_order_customer_date
ON customer_order (customer_id, placed_at DESC);
-- the operator dashboard only ever looks at open orders (~3% of rows)
CREATE INDEX idx_order_open
ON customer_order (placed_at DESC)
WHERE status IN ('PLACED','PAID');
-- keyset pagination over the whole table
CREATE INDEX idx_order_keyset
ON customer_order (placed_at DESC, order_id DESC);
-- metadata filters from the advanced search
CREATE INDEX idx_order_metadata
ON customer_order USING gin (metadata jsonb_path_ops);
-- the aggregate load: fetch all lines for an order
CREATE INDEX idx_line_order ON order_line (order_id);
-- the outbox poller: tiny index over a growing table
CREATE INDEX idx_outbox_pending
ON outbox_event (event_id) WHERE published_at IS NULL;
-- audit timeline
CREATE INDEX idx_event_order ON order_event (order_id, occurred_at DESC);
Every index above exists because a specific screen issues a specific query. Adding an index "because we might filter on it" costs write throughput forever for a benefit that never arrives. Chapter 5 of the PostgreSQL course shows how to prove which ones earn their keep.
Generating the order reference
CREATE SEQUENCE order_reference_seq;
-- ORD-2026-000123: readable, sortable, and it does not leak total volume
-- as directly as a bare primary key
CREATE OR REPLACE FUNCTION next_order_reference() RETURNS text
LANGUAGE sql VOLATILE AS $$
SELECT 'ORD-' || to_char(now(), 'YYYY') || '-' ||
lpad(nextval('order_reference_seq')::text, 6, '0');
$$;
ALTER TABLE customer_order
ALTER COLUMN reference SET DEFAULT next_order_reference();
Migrations
spring:
datasource:
url: jdbc:postgresql://localhost:5432/oms
username: oms_app
password: ${DB_PASSWORD}
flyway:
enabled: true
locations: classpath:db/migration
validate-on-migrate: true
baseline-on-migrate: false
1. Migrations are immutable once merged. Fix a mistake with a new file,
never by editing an applied one — Flyway checksums them.
2. Every migration starts with SET lock_timeout = '3s'; so a
blocked schema change fails instead of queueing every query behind it.
3. Migrations must be backwards compatible: during a rolling deploy the
old and new application versions run against the same schema.
Seed data for development
INSERT INTO customer (email, full_name) VALUES
('ada@example.com', 'Ada Lovelace'),
('grace@example.com', 'Grace Hopper');
INSERT INTO product (sku, name, price, stock_qty) VALUES
('SKU-KB-01', 'Mechanical keyboard', 129.00, 40),
('SKU-MS-02', 'Ergonomic mouse', 69.50, 120),
('SKU-MN-03', '27" monitor', 349.00, 15);
-- 5,000 orders so the list screen and EXPLAIN plans are realistic
INSERT INTO customer_order (customer_id, status, total_amount, placed_at)
SELECT 1 + (random() * 1)::int,
(ARRAY['PLACED','PAID','FULFILLED','DELIVERED','CANCELLED'])
[1 + floor(random() * 5)]::order_status,
round((random() * 900 + 20)::numeric, 2),
now() - (random() * 365) * interval '1 day'
FROM generate_series(1, 5000);
Five rows of test data hides every performance problem you are about to create. Seed enough that a missing index is visible immediately.
Why enforce "quantity > 0" with a CHECK constraint rather than only in the service?
Application validation still belongs in the service, for good error messages. But the service is not the only writer: manual SQL during an incident, a nightly import, or a second application all reach the table directly. A constraint holds for every one of them.