Chapter 15 / 15 · Webster International
Real Systems: Architecture Blueprints
Walk through a shopping cart, click funnel, bookings, calendar aggregator, music directory, authentication and mobile synchronization end-to-end.
The most useful architecture lessons combine users, screens, APIs, data, failure cases and verification into one complete journey.
01 / FIELD NOTE
Blueprint 1 · Shopping cart and checkout
Mental model: checkout is a durable state machine, not a sequence of browser screens. The browser owns a temporary cart; the server recomputes prices and tax, reserves inventory atomically, and records a stable order ID. A payment provider owns payment outcome, while a verified webhook changes the local order state. Model transitions (draft → pending → paid → fulfilled) with unique event IDs, durable inbox/outbox records and reconciliation for missed notifications. Do not equate an HTTP redirect with settlement.
A retried checkout or webhook must not charge twice, decrement stock twice, or ship an unpaid order. Clear ownership also makes refunds and chargebacks auditable.
Scenario A: a customer double-clicks Pay during a slow mobile connection; one server-side idempotency key maps both attempts to one order/payment intent. Scenario B: a digital-download store receives the same payment-success webhook twice; only the first verified, committed transition grants access. Both require a refund/reversal path.
// Runnable Node.js model only: assumes a VERIFIED provider event.
const orders = new Map([['o1', {state:'pending', seen:new Set()}]]);
function applyVerifiedEvent(id, eventId, kind) {
const o = orders.get(id);
if (!o || o.seen.has(eventId)) return o?.state ?? 'missing';
o.seen.add(eventId);
if (kind === 'paid' && o.state === 'pending') o.state = 'paid';
if (kind === 'refund' && o.state === 'paid') o.state = 'refunded';
return o.state;
}
console.log(applyVerifiedEvent('o1','evt1','paid'));
console.log(applyVerifiedEvent('o1','evt1','paid')); // no duplicate transitionHands-on exercise · reveal the verification check
Run the snippet, then add a refund event evt2 and replay evt1. Confirm the state never returns to paid. Sketch the database unique constraint on (provider,event_id), the order transition transaction and a reconciliation job for missing webhooks.
First two lines print paid, paid. After evt2, state is refunded; replaying evt1 leaves refunded. A real implementation verifies signatures, persists dedupe before acknowledgement, and never trusts a browser success URL.
02 / FIELD NOTE
Blueprint 2 · Click funnel / campaign journey
Mental model: a campaign funnel is a consent-aware series of independently measurable state transitions, not a single form-submit metric. A landing page communicates value and a clear action; the browser provides labels and forgiving validation; the server validates input and consent, deduplicates leads, writes a CRM record and queues only permitted follow-up. Analytics should record anonymous stage transitions, never raw form contents. Keep a separate provenance record for the consent text/version and timestamp.
An apparently successful funnel can quietly lose leads, spam non-consenting visitors or count duplicate clicks as conversions. Explicit stage ownership makes recovery and auditing possible.
Scenario A: a home-inspection inquiry chooses callback rather than full registration; the server saves a contact request and a consent flag without inventing an account. Scenario B: a musician venue booking form accepts a long description and an optional newsletter opt-in; a CRM lead is created but marketing email is withheld when opt-in is false.
// Runnable Node.js: no network or personal data in telemetry.
const events = [];
function submitLead(input) {
const email = String(input.email || '').trim();
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email))
return {ok:false, error:'Enter a valid email address'};
const record = {email, marketingConsent:input.marketingConsent === true};
events.push({step:'lead_accepted', marketingConsent:record.marketingConsent});
return {ok:true, record};
}
console.log(submitLead({email:'a@example.test',marketingConsent:false}).ok);
console.log(events); // email deliberately absentHands-on exercise · reveal the verification check
Submit one invalid email and two valid leads with opposite consent flags. Verify invalid input never emits a success event, marketing opt-out stays false, and no email address appears in telemetry. Draft accessible field-level error text.
Invalid returns ok:false; valid returns ok:true; event payloads include only stage and consent boolean. This is a pure model, not a production email validator or a substitute for server security controls.
03 / FIELD NOTE
Blueprint 3 · Booking and appointment scheduling
Mental model: a displayed calendar slot is a projection; the authoritative booking is an atomic claim on a resource and a half-open time interval [start,end). Model availability from resource capacity, operating hours, existing bookings, holds and buffer time. Convert a user-entered local time with an IANA zone to an instant while retaining the zone for future display. Enforce exclusivity in the database, not with a disabled button; PostgreSQL range exclusion constraints are one approach.
Two customers can select the same apparently free slot before either request commits. Daylight-saving gaps and repeated local hours create a second class of errors that ordinary string comparisons miss.
Scenario A: two dog-walking dispatchers reserve the last six-dog pickup capacity concurrently; a transaction or guarded capacity counter accepts only one excess claim. Scenario B: a home inspector books a 90-minute visit spanning a timezone change; the API stores UTC instants plus America/Toronto and asks for clarification on ambiguous local times.
// Runnable Node.js: overlap logic only, NOT a transaction.
const overlap = (a,b) => a.start < b.end && b.start < a.end;
const utc = s => Date.parse(s); // require ISO timestamp with Z
const booked = {start:utc('2026-11-02T14:00:00Z'),
end:utc('2026-11-02T15:00:00Z')};
const touching = {start:booked.end,end:utc('2026-11-02T16:00:00Z')};
const racing = {start:utc('2026-11-02T14:30:00Z'),end:touching.end};
console.log(overlap(booked,touching), overlap(booked,racing));Hands-on exercise · reveal the verification check
Run the interval test, then change the second candidate to start one millisecond before booked.end. Explain how a concurrent insert can still double-book without a database constraint. Write one DST ambiguity test for America/Toronto.
Original output is false true; the one-millisecond change produces true. A robust backend rejects conflicting committed intervals and explicitly resolves nonexistent/ambiguous local times before storage.
04 / FIELD NOTE
Blueprint 4 · Community headlines and events aggregator
Mental model: a local-news aggregator is an evidence-preserving ingestion pipeline: fetch permitted source → parse → normalize → deduplicate → review → publish → correct/retract. Keep source URL, retrieval time, publisher, license/usage rights and original timestamp separate from editorial headline and local community tags. A scheduled import can be retried safely using a stable source key; the public page reads approved records, not raw crawler output.
More scraped records do not imply a better local-news product. Without provenance, duplicate control and correction workflows, stale events and invented facts can spread across every town view.
Scenario A: two municipal RSS feeds syndicate the same road closure; canonical source identity and a reviewer merge them while preserving both references. Scenario B: an event date changes after publication; the importer marks a proposed update and a reviewer confirms before the calendar is amended.
// Runnable Node.js: illustrative normalization; no fetching.
function sourceKey(raw) {
const u = new URL(raw);
if (!['https:','http:'].includes(u.protocol)) throw Error('bad scheme');
for (const key of ['utm_source','utm_medium','utm_campaign']) u.searchParams.delete(key);
u.hash = '';
return u.toString();
}
const a='https://town.example/events/7?utm_source=mail';
const b='https://town.example/events/7';
console.log(sourceKey(a) === sourceKey(b)); // trueHands-on exercise · reveal the verification check
Test duplicate URLs with tracking parameters, then compare URLs whose meaningful event IDs differ. Sketch an editorial state machine: imported → needs_review → approved → corrected/retracted. Decide which fields cannot be overwritten by AI.
Tracking-only variants compare equal; different event IDs remain distinct. Every published item retains original source, timestamp, reviewer decision and correction history. This snippet does not establish permission to crawl a site.
05 / FIELD NOTE
Blueprint 5 · Artist atlas and media discovery
Mental model: an artist atlas is a normalized graph with distinct artist, album, track, recording, performance, venue and media-link identities. Views are projections of those shared records, not separately edited copies. A source assertion carries attribution and confidence; a public artist profile should distinguish verified facts, missing data and user-submitted suggestions. Video URLs remain external identifiers and embeds should be opt-in to avoid heavy third-party loads.
Duplicating biographies and album lists between a jazz showcase, music events calendar and artist directory produces contradictions, broken links and expensive manual corrections.
Scenario A: one album appears on an artist profile and a jazz-funk discovery carousel through the same release ID, with cover-license provenance. Scenario B: a live performance is linked to both venue and artist, while an unofficial fan-uploaded video is clearly labeled and not mistaken for the artist's official channel.
// Runnable Node.js: shared facts projected into two views.
const artists=[{id:'a1',name:'Example Ensemble'}];
const releases=[{id:'r1',artistId:'a1',title:'Live Session'}];
const gigs=[{id:'g1',artistId:'a1',venue:'Community Hall'}];
const profile=id=>({
artist:artists.find(a=>a.id===id),
albums:releases.filter(r=>r.artistId===id),
shows:gigs.filter(g=>g.artistId===id)
});
console.log(profile('a1').albums.length, profile('a1').shows.length);Hands-on exercise · reveal the verification check
Add a second artist and a collaboration without duplicating the original album. Render a missing-cover placeholder with descriptive text. Identify which source field proves a video is official rather than merely uploaded.
Profile a1 initially prints 1 1. After adding a collaboration join, both artists can reference one release ID. Missing cover is not represented as a broken image or a fabricated licensed asset.
06 / FIELD NOTE
Blueprint 6 · Login, roles and project-scoped CRM
Mental model: authentication proves a session identity; authorization decides whether that identity may perform an action on this exact tenant-owned object. Each CRM request must resolve a trusted tenant scope from the authenticated session and apply it to reads, writes, exports, files and audit history. Role checks and ownership checks are independent. Model invoices, bookings and client records with immutable tenant IDs and a revision for concurrent edits.
A correct login page is irrelevant if changing /invoices/42 to /invoices/43 reveals another customer's records. Tenant isolation must survive direct API calls, pagination and background jobs.
Scenario A: a dog-walking employee can read their own project bookings but not the home-inspection project's invoices, even when both use the same CRM UI. Scenario B: a client portal can see only invoices linked to its authenticated client identity, while a business admin can audit permitted project records.
// Runnable Node.js: an illustrative scoped lookup.
const invoices=[
{id:'i1',tenantId:'dogs',amount:35},
{id:'i2',tenantId:'inspect',amount:200}
];
const readInvoice=(session,id)=>invoices.find(
x=>x.id===id && x.tenantId===session.tenantId
) || null;
console.log(readInvoice({tenantId:'dogs'},'i1')?.amount);
console.log(readInvoice({tenantId:'dogs'},'i2'));Hands-on exercise · reveal the verification check
Attempt to read the second tenant's invoice with the first tenant's session, then test an authorized user with a missing role. Extend the model to require both tenant ownership and permission for PATCH. State the equivalent SQL WHERE clause.
Output is 35 and null. A real handler also authenticates the session, checks action permission, and uses WHERE id = ? AND tenant_id = ? inside the database transaction; UUIDs alone are not authorization.
07 / FIELD NOTE
Blueprint 7 · Mobile companion with offline sync
Mental model: offline-first mobile uses a local read model plus a durable outbox of user intentions. Every queued mutation carries a stable client-generated operation ID, base server revision and actor scope. Sync is a protocol: authenticate → send bounded batch → deduplicate → apply or return conflict → fetch deltas → reconcile. Server constraints remain authoritative; notifications only hint that fresh data may exist.
A field worker must be able to record a visit without connectivity, but reconnecting must not silently overwrite a colleague's newer edit or create duplicate bookings.
Scenario A: a dog walker records pickup while offline; the app shows Pending sync until the server accepts the operation ID and updates the visit revision. Scenario B: a home inspector edits a note offline while an office worker edits the same record; the server returns 409 and the app offers a readable merge/review screen.
// Runnable Node.js: version-based conflict, not a real sync server.
function applyEdit(server, edit) {
if (edit.baseRevision !== server.revision)
return {status:409, current:server};
return {status:200, current:{
...server, note:edit.note, revision:server.revision+1
}};
}
const current={note:'Arrived',revision:4};
console.log(applyEdit(current,{note:'Done',baseRevision:3}).status);
console.log(applyEdit(current,{note:'Done',baseRevision:4}).current.revision);Hands-on exercise · reveal the verification check
Run the snippet, then simulate two offline edits from revision 4 arriving in sequence. Ensure the first increments the revision and the second produces a conflict. Describe a user-visible resolution that never silently loses the second note.
Output is 409 then 5. Sequential edits based on the same revision result in one success and one conflict. The operation ID must be persisted for retry deduplication in a real service.
08 / FIELD NOTE
Blueprint 8 · A practical AI-assisted workflow
Mental model: a model proposes a candidate; deterministic application code owns schemas, permissions, citations and side effects. The pipeline is retrieval with source provenance → bounded model extraction → schema validation → factual cross-check → risk-based review → approved commit → monitoring and rollback. Structured output constrains shape but does not prove truth. Separate candidate, reviewed and published states, and keep model version/prompt/evaluation results for traceability.
Plausible AI output can invent event dates, mix artist identities or misclassify a service inquiry. Publication and customer-facing actions need evidence, not merely valid JSON.
Scenario A: an assistant extracts a concert date from a venue listing; an editor checks the primary source before the event appears in the public calendar. Scenario B: a model proposes a dog-training lesson or accessibility remediation; a subject expert checks safety and WCAG applicability before content becomes authoritative.
// Runnable Node.js: model output is UNTRUSTED input.
function approve(candidate, reviewer) {
if (!candidate || typeof candidate.title !== 'string'
|| !/^https:\/\/[^ ]+$/.test(candidate.sourceUrl)
|| reviewer?.approved !== true) return {published:false};
return {published:true, title:candidate.title, source:candidate.sourceUrl};
}
const draft={title:'Community concert',sourceUrl:'https://venue.example/event'};
console.log(approve(draft,{approved:false}).published);
console.log(approve(draft,{approved:true}).published);Hands-on exercise · reveal the verification check
Feed the gate missing source URLs, a false review flag and an approved sourced item. Extend it to validate allowed source hosts, actual source dates and an immutable reviewer ID. Create a five-case evaluation set including one prompt-injection attempt.
Output is false then true. Missing source/reviewer fails closed. In production, schema validation, trusted-host parsing, independent source verification, tool sandboxing and a durable audit log must precede publication.
RESEARCH EXPANSION · APPLIED ENGINEERING
End-to-end checkout race and duplicate charge blueprint
Model cart quote, inventory reservation, order, payment attempt, verified webhook and fulfilment as separate states. Guard inventory atomically, use payment idempotency keys and reconcile delayed responses.
The last item can be purchased twice or charged twice if retry semantics are unspecified.
Two simultaneous buyers request one final item; only one reservation succeeds and an echoed webhook cannot create another charge.
Hands-on exercise · reveal the verification check
Simulate concurrent purchase, webhook retry and lost HTTP response.
One paid order, consistent stock and no duplicate fulfilment.
Lead-generation funnel with consent and auditability
Make the offer clear, minimise required fields, prevent bots and write submissions to CRM with opt-in status, timestamp, source and unsubscribe lifecycle. Event instrumentation should capture funnel steps without logging email or message text.
Conversion data is useless if forms mislead users or violate consent requirements.
Campaign → landing → validated contact → confirmation → consent-aware queue → CRM opportunity with attribution.
Hands-on exercise · reveal the verification check
Run keyboard and error-state tests with an intentionally malformed email.
No consent is assumed and CRM stores one deduplicated lead.
Multi-source local-news ingestion with evidence
Collect permitted feeds, record canonical URLs and timestamps, normalise communities, detect duplicates, and keep source attribution. Expose different views through one query API and mark stale or unverified records.
A high article count is meaningless without identity, freshness and traceable source support.
A headline from Stayner and a shared regional syndication link merge into one story with two sources.
Hands-on exercise · reveal the verification check
Import identical source pages twice and modify an update date.
No duplicate story; provenance and last-checked time persist.
Booking availability and time-zone correctness
Represent availability as durable resources, constraints and holds. Store instants in UTC along with venue time-zone metadata; check slots transactionally and communicate hold expiry to clients.
DST changes and simultaneous reservations can create conflicts despite perfect-looking calendars.
A Friday 7 pm slot in Toronto remains correctly timed across daylight saving changes and another user reserving it.
Hands-on exercise · reveal the verification check
Test booking around fall-back DST and two concurrent clients.
Stored slot has one unambiguous instant and one successful reservation.
Artist directory and media relationship model
Use one canonical Artist, Release, Performance, Venue, Media and Source model with junction tables; render pocket, showcases and music board as different projections. Introduce completeness scores and source verification timestamps.
Duplicate curated JSON cards diverge and media links decay independently.
An album appears in artist discography once, while a performance joins all artists on stage and its ticket venue.
Hands-on exercise · reveal the verification check
Model a collaboration with two artists on one record and one show.
Every page resolves to the same canonical IDs and references.
Multi-tenant CRM with secure object ownership
A project-scoped CRM must enforce tenant checks in queries, file retrieval, exports, invoices, email sending and audit logs; one shared login token must not grant access across arbitrary project IDs.
The biggest architecture risk is accidental cross-client disclosure through guessed URLs or exports.
A consultant logged into customer A changes an invoice URL to B; server returns 403/404 without leaking B's metadata.
Hands-on exercise · reveal the verification check
Build tenant isolation tests for list, detail, export and update.
All four reject foreign-tenant object IDs.
Blueprint extensions
Blueprint 9 · Multi-tenant service CRM with bookings and calendar projections
Model tenants, clients, services, booking instances, statuses, staff assignments, invoices and audit records in a relational schema. Keep booking mutations authoritative in one module and project them into calendar or map read models. Enforce tenant ownership and concurrency-safe availability before displaying operational dashboards.
A client entry is not the same as a booking or invoice, even when the UI combines them.
Create a booking for a client, change its time, cancel it and verify calendar projection, notification job and audit history are consistent.
CREATE TABLE bookings (
id BIGINT PRIMARY KEY,
tenant_id BIGINT NOT NULL,
client_id BIGINT NOT NULL,
starts_at TIMESTAMPTZ NOT NULL
);Hands-on exercise · reveal the verification check
Draw the write model, calendar projection and four cross-tenant tests.
Each view derives from a durable authorized booking state.
Blueprint 10 · Route optimizer for delivery and dog walking
Represent route stops as address-backed coordinates with time windows, visit duration, vehicle capacity and start/end constraints. Geocode with a trusted provider, use a road-network routing matrix where available, and separate manual drag order from suggested optimization. Show estimated versus actual travel and allow undo.
Straight-line nearest-neighbor ordering is not necessarily the fastest valid route.
Optimize eight pickups with preferred arrival windows, then re-order two stops manually on mobile and compare total travel estimates.
const stops = [{id:'a',windowStart:'09:00'},{id:'b',windowStart:'10:30'}];
// Route solver must honor windows and road travel times.Hands-on exercise · reveal the verification check
Specify a route objective, constraints and a manual override test.
Suggested order respects visit windows and all saved stops.
Blueprint 11 · Time-slider geospatial business intelligence
Build a day-indexed query over 90 days of bookings and activity, with deterministic time-zone handling and meaningful visual legend. Map pins show location-backed events while charts aggregate count, revenue, cancellations and travel cost for the selected range. Distinguish empty days from missing data.
Spatial and temporal views reveal patterns not visible in static client lists.
Move the slider to a busy date, highlight seven stops, inspect source bookings and compare service density with earlier weeks.
SELECT date_trunc('day', starts_at) AS day, COUNT(*) AS bookings
FROM bookings WHERE starts_at >= NOW() - INTERVAL '90 days'
GROUP BY 1 ORDER BY 1;Hands-on exercise · reveal the verification check
Define the SQL query, daily aggregates and map state contract.
Changing the date updates map and charts without stale rows.
Blueprint 12 · Headline and event ingestion with source provenance
Collect permitted feeds with stable external IDs and canonical source URLs; normalize locations, dates, time zones and title text. Deduplicate conservatively, quarantine uncertain events and show published-at versus observed-at separately. Schedule refreshes with retries and maintain a source-health dashboard.
Automated content becomes misleading when duplicates and stale results look like new events.
Ingest town news from two providers and preserve each item’s source link, attribution, correction history and last-seen time.
// Import key = source_id + external_event_id
// Record canonical_url, fetched_at, published_at and parse confidence.Hands-on exercise · reveal the verification check
Create a sample ingestion spec for twenty real event records.
Repeated import neither duplicates nor silently rewrites evidence.
Blueprint 13 · Artist discovery catalogue with normalized media assets
Model artist identities, aliases, releases, tracks, genres, credits, sources and media rights separately. Link playlists and external video providers through stable IDs and render responsive album artwork with provenance. Shared data powers gallery and showcase views while distinct interfaces preserve their purposes.
One reliable artist record should feed several experiences without duplicating biography and discography data.
Create a source-backed artist with three releases, cover metadata and twenty embeddable or linked videos.
// Data model: artist -> releases -> tracks
// video references carry provider, external ID and provenance.Hands-on exercise · reveal the verification check
Diagram the artist, release and video relationships.
A change to the artist record appears in both consuming views.
Blueprint 14 · AI-assisted editorial operations with approval gates
Build a bounded AI pipeline: acquire source, extract candidate facts, validate identifiers, enrich through approved references, flag uncertainty and present a review queue. Record prompt/model provenance and outcomes, then publish only approved records. Use evaluation cases to measure hallucinations and duplicate detection.
AI enrichment can increase throughput without transferring publishing authority to unreliable guesses.
Extract a town event from a news item, verify date and venue against evidence, then require editor approval before publication.
// Review states: proposed -> evidence_checked -> approved -> published
// Reject if provenance cannot be verified.Hands-on exercise · reveal the verification check
Define a review queue with approve, reject and revise paths.
Every published fact has provenance and approval status.