Chapter 10 / 15 · Webster International
Architecture & Distributed Systems
Monoliths, microservices, events, queues, schedulers, caching, consistency, scalability, reliability and technical decision records.
Architecture is a set of choices about boundaries, failure modes, data ownership, communication and how a system changes over time.
01 / FIELD NOTE
Modular monoliths and layered systems
Mental model: a modular monolith is one deployable process with many enforceable business boundaries, not a single shared bag of functions. Domain rules point inward; HTTP controllers and database adapters depend on domain interfaces, not the reverse. A module owns its public API, tables and invariants. Keep a dependency graph and reject forbidden imports in CI. Start with one transaction boundary and extract a service only when an independently measurable deployment or scaling need exists.
It shortens local debugging and deploy/recovery paths while keeping future extraction possible. A modular boundary can be tested without a network, and a local database transaction can protect multiple related writes.
Scenario A — a dog-walking CRM keeps Bookings, Billing and Notifications in separate folders; a booking use case invokes an exported billing port rather than importing its tables. Scenario B — a music-events importer shares one deployable app with the public calendar but runs its crawl through an explicit ingestion interface. Inspect a dependency graph when a change unexpectedly touches unrelated modules.
// Runnable Node.js 20+ — illustrative dependency-boundary test
const assert = require('node:assert/strict');
const edges = [['http','bookings'],['bookings','billing-port'],['billing-adapter','billing-port']];
const forbidden = edges.filter(([from,to]) => from==='bookings' && to==='billing-db');
assert.deepEqual(forbidden, []);
assert(edges.some(([a,b]) => a==='bookings' && b==='billing-port'));
console.log('Module boundary respected');Hands-on exercise · reveal the verification check
Draw the Bookings → Billing dependency arrows and add a forbidden Bookings → billing-db edge to the snippet. Run with node; then implement a repository lint rule for your real folder structure.
Original prints 'Module boundary respected'. Your deliberate forbidden edge must fail after you assert forbidden.length === 0. No domain module imports another module's private persistence adapter.
02 / FIELD NOTE
Microservices and data ownership
Mental model: a microservice owns one business capability, its private data model and its release lifecycle. A network boundary introduces latency, partial failure, authentication, schema evolution and eventual consistency. A 'service' sharing another service's tables is not independent. Evaluate deployment frequency, team ownership, data change coupling and measured hotspots before extraction; prefer coarse business boundaries over a service per CRUD entity.
Independent releases and scaling can unlock larger organizations, but only when the added platform and observability cost is justified. Explicit ownership also prevents one team's schema migration from silently breaking another team.
Scenario A — a ticket marketplace extracts Payments because payment security and reconciliation have a distinct owner and failure budget; Checkout calls a versioned contract, never payment SQL. Scenario B — a small community-news site retains ingestion and editorial review in one app because one team deploys both together. For an outage, follow request ID through the gateway and service traces.
// Runnable Node.js 20+ — illustrative ownership contract
const assert = require('node:assert/strict');
const ownership = {bookings:'booking-db',payments:'payment-db'};
function canReadDirectly(service,store){return ownership[service]===store;}
assert.equal(canReadDirectly('bookings','payment-db'),false);
assert.equal(canReadDirectly('payments','payment-db'),true);
console.log('Cross-service SQL denied; use the Payments API');Hands-on exercise · reveal the verification check
Map a CRM's Booking, Payment and Reminder capabilities to data owners; simulate a direct booking query into payment-db and replace it with a Payments API contract. Record a threshold that would justify extraction.
The direct read returns false; a Payments-owned read returns true. Your decision names deployment ownership, consistency cost and a measurable reason for a network boundary.
03 / FIELD NOTE
Publish–subscribe and event-driven systems
Mental model: a domain event is a past-tense fact with an immutable ID, type, version, aggregate ID and timestamp. Publish-subscribe fans one fact out to many interested consumers; a work queue distributes one task among competing workers. At-least-once delivery means duplicates are normal; ordering may only hold per key. Store state and outbox event atomically, then publish asynchronously. Consumers deduplicate by event ID and tolerate replay.
Independent calendar, search and notification projections can evolve without modifying the booking write path. Durable events make recovery and new subscribers possible, provided replay semantics are explicit.
Scenario A — BookingConfirmed v1 drives an email subscriber and a route-map projection; a redelivery must not email the same customer twice. Scenario B — ArtistPublished updates a search index and a public feed independently; the index can lag while the publication remains committed. Trace event ID and consumer offset to diagnose missing projections.
// Runnable Node.js 20+ — illustrative idempotent consumer
const assert = require('node:assert/strict');
const processed = new Set(), delivered = [];
function consume(e){if(processed.has(e.id)) return 'duplicate'; processed.add(e.id); delivered.push(e.bookingId); return 'processed';}
const event={id:'evt-42',type:'BookingConfirmed',version:1,bookingId:'B17'};
assert.equal(consume(event),'processed');
assert.equal(consume(event),'duplicate');
assert.deepEqual(delivered,['B17']);
console.log('One side effect from two deliveries');Hands-on exercise · reveal the verification check
Deliver the same event three times and add a new v2 event with an optional route ID. Make the consumer ignore duplicates and tolerate the optional field; sketch a transactional outbox table.
Only one side effect for evt-42; v2 processes once with a new ID. Explain why a process-local Set is NOT durable deduplication and would be replaced by a transactional unique key.
04 / FIELD NOTE
Scheduled jobs, polling and housekeeping
Mental model: a schedule is a request to attempt work, not a guarantee that exactly one run completes. A job has a stable logical run key, a lease/lock with expiry, a checkpoint, retry policy and outcome record. Choose UTC intervals versus local civil times deliberately: daylight-saving transitions can skip or repeat wall-clock times. Split large batches into resumable pages and budget their time; jitter non-urgent starts to avoid hourly spikes.
Recurring imports and billing reconciliation must survive restarts, delayed invocations and overlapping workers without duplicate charges, missed pages or uncontrolled retry storms.
Scenario A — a news crawler runs hourly, claims 2026-10-27T07 as its run key, checkpoints each source page and retries only failed sources. Scenario B — a nightly invoice job uses tenant+invoice-period as the idempotency key and cannot send a second invoice after a retry. Compare scheduler history to durable job-run records when a report is missing.
// Runnable Node.js 20+ — illustrative durable-key model (in memory only)
const assert = require('node:assert/strict');
const completed = new Set();
function run(key,task){if(completed.has(key)) return 'skipped'; task(); completed.add(key); return 'done';}
let invoices=0;
assert.equal(run('tenantA:2026-10',()=>invoices++),'done');
assert.equal(run('tenantA:2026-10',()=>invoices++),'skipped');
assert.equal(invoices,1);
console.log('One invoice for one logical period');Hands-on exercise · reveal the verification check
Run the same tenant-period twice, then a second period. Simulate a crash after the side effect but before completed.add(key), and describe the required transactional/idempotent external API fix.
The duplicate period is skipped; a new period executes once. The crash case demonstrates why an in-memory Set alone cannot guarantee exactly-once external effects.
05 / FIELD NOTE
Consistency, eventual consistency and sagas
Mental model: ACID applies inside one transactional boundary; a saga is a durable state machine coordinating committed local transactions. Record each step, idempotency key and compensating action. A compensation is a new business operation, not a time machine: a refund is not the same as never charging. Identify irreversible pivot steps, timeouts, retries, manual review and the user-visible 'pending' state.
Checkout and booking flows often cross inventory, payment and notification systems. Explicit state and compensation prevent a partial failure from silently creating a double charge or a phantom reservation.
Scenario A — reserve a dog-sitting slot, authorize payment, confirm; on authorization failure release the slot and mark booking declined. Scenario B — concert tickets are reserved before a payment provider callback; a timeout leaves payment status unknown and requires reconciliation before issuing a refund. Inspect the saga ID and each participant's durable status.
// Runnable Node.js 20+ — illustrative saga compensation
const assert = require('node:assert/strict');
const state={reserved:false,status:'new'};
function reserve(){state.reserved=true;state.status='reserved';}
function release(){state.reserved=false;state.status='declined';}
function authorizePayment(){throw new Error('provider declined');}
reserve();
try{authorizePayment();state.status='confirmed';}catch{release();}
assert.deepEqual(state,{reserved:false,status:'declined'});
console.log('Failed payment released reservation');Hands-on exercise · reveal the verification check
Extend the saga with payment status 'unknown' after timeout; do not immediately retry with a new key. Add a reconciliation transition and a compensation-failed alert.
Declined payment releases reservation; unknown payment remains pending until provider lookup. A failed compensation is recorded and escalated, not silently considered rolled back.
06 / FIELD NOTE
Load balancers, CDN, replicas and capacity
Mental model: capacity is constrained by the slowest shared dependency, not by the number of web replicas. Estimate offered load (requests/second), average service time, concurrent work and safe utilization; then measure p95/p99 latency under realistic peaks. CDN caching is safe for public, versioned assets, not private personalized responses. Separate read replicas from write capacity and document replication lag.
Adding servers without a capacity model can amplify database contention and cost. Correct caching and stateless sessions keep the site responsive when more users arrive.
Scenario A — a music-events listing caches public poster images with versioned URLs while user-specific invoices use private/no-store responses. Scenario B — a route planner receives 140 requests/s at a 35 ms service time; estimate concurrency before load testing, then find the database bottleneck. Track cache hit ratio, DB pool wait and queue depth.
// Runnable Node.js 20+ — illustrative capacity estimate, NOT sizing advice
const assert = require('node:assert/strict');
const rps=140, serviceMs=35, targetUtilization=0.70;
const averageConcurrent=rps*serviceMs/1000;
const slots=Math.ceil(Number((averageConcurrent/targetUtilization).toFixed(8)));
assert.equal(Number(averageConcurrent.toFixed(1)),4.9);
assert.equal(slots,7);
console.log({averageConcurrent,slots});Hands-on exercise · reveal the verification check
Recalculate at 280 requests/s and 70 ms; compare with measured p95, DB pool capacity and cache hit rate. Mark public and private HTTP responses with appropriate cache policies.
Average concurrency becomes 19.6 and illustrative slots become 28 at 70% target utilization. This is not a server count or an SLO: benchmark actual CPU, I/O and shared dependencies.
07 / FIELD NOTE
Failure domains, resilience and backpressure
Mental model: every dependency call consumes a finite latency and concurrency budget. A timeout bounds waiting, a circuit breaker temporarily stops known-bad calls, a bulkhead reserves capacity for critical work, and a bounded queue rejects excess load instead of hiding an outage. Retry only transient, safe/idempotent operations with capped backoff and jitter. Decide which features can degrade to cached data.
A broken ticket provider must not exhaust threads and memory for a public community-news site. Controlled failure preserves core functionality and gives operators signals to act on.
Scenario A — a route-optimization provider times out; show saved route order and a textual warning while letting staff edit stops. Scenario B — a concert feed API returns 503; serve cached event summaries, cap retries and isolate the importer queue from the booking API. Diagnose request budget, rejection rate and dependency error trend.
// Runnable Node.js 20+ — illustrative bounded admission
const assert = require('node:assert/strict');
const queue=[];const limit=2;
function admit(id){if(queue.length>=limit)return {status:503,retryAfter:2};queue.push(id);return {status:202};}
assert.equal(admit('job-a').status,202);
assert.equal(admit('job-b').status,202);
assert.deepEqual(admit('job-c'),{status:503,retryAfter:2});
console.log('Overload rejected rather than buffered forever');Hands-on exercise · reveal the verification check
Change the queue limit to one, add a completion method, then inject a dependency outage. Design a UI message with text status and retry action; draw where bulkheads isolate public reads from imports.
The second request is rejected while capacity is full and accepted after completion. Queue length remains bounded; an outage cannot indefinitely consume memory or block unrelated reads.
08 / FIELD NOTE
Architecture Decision Records and sequence diagrams
Mental model: an Architecture Decision Record is a versioned explanation of one consequential choice, not a permanent commandment. Capture context, alternatives, decision, consequences, status, owner and reconsideration trigger. A sequence diagram traces the happy path AND timeout, retry, authorization and compensation paths; a deployment diagram states what actually runs, not what is planned.
Future engineers can understand why SQLite was selected, when it becomes unsafe and how to revisit it without repeating the same debate. Diagrams expose cross-boundary calls that prose often hides.
Scenario A — ADR-004 keeps a single PostgreSQL database until independent tenant scaling is measured; include rollback, ownership and migration triggers. Scenario B — a dog-booking sequence shows browser → API → auth → booking transaction → outbox → notification, including failed payment and retry. Validate the diagram against traces and the current deployment manifest.
// Runnable Node.js 20+ — illustrative ADR completeness check
const assert = require('node:assert/strict');
const adr={status:'proposed',context:'One deployment and one writer',options:['SQLite','PostgreSQL'],decision:'Use SQLite initially',consequences:'Simple ops; limited multiwriter scaling',revisitWhen:'More than one writer required'};
for(const key of ['status','context','options','decision','consequences','revisitWhen'])assert(adr[key]?.length>0,key);
assert(adr.options.length>=2);
console.log('Decision has alternatives and revisit trigger');- AWS ADR FAQ and minimum contents ↗
- AWS ADR best practices ↗
- OpenTelemetry signals for diagram verification ↗
Hands-on exercise · reveal the verification check
Write an ADR choosing a modular monolith versus microservices for a 3-person team. Draw a booking sequence including unauthorized access, timeout and compensation; mark actual versus proposed deployment components.
ADR includes at least two alternatives, costs, an owner/status and measurable revisit trigger. Sequence identifies every actor, trust boundary, error path and a textual equivalent for readers who cannot see the diagram.
RESEARCH EXPANSION · APPLIED ENGINEERING
Modular monolith first, microservices for proven needs
Keep business boundaries modular inside one deployable until distinct teams, workloads or independent release cycles justify splitting. Make data ownership and module contracts explicit from day one.
Distributed deployments introduce new consistency, observability, authentication and failure modes.
One venue/events service can own calendar, ingestion and public reads as modules before extracting a search service.
Hands-on exercise · reveal the verification check
Draw a monolith module dependency graph and forbidden cross-module calls.
Modules share stable interfaces, not arbitrary table internals.
Event outbox and at-least-once delivery
Write domain state and an outbox event in the same database transaction, then publish asynchronously. Consumers record message IDs or design idempotent updates because retries may deliver the same event again.
Sending a message outside the transaction risks a committed order with no event or a phantom event for a rolled-back order.
Commit OrderPaid plus outbox row; worker publishes; subscriber dedupes before creating the receipt.
Hands-on exercise · reveal the verification check
Kill publisher after commit and replay the event twice.
Receipt created once and outbox eventually clears.
CQRS projections and eventual consistency
Write models validate commands, while read models can be materialized for fast search and calendars. Document projection lag, reprocessing and how to rebuild from authoritative history.
Read queries and write invariants have different optimisation needs, but separate projections add complexity.
A performance record commits in SQL, then an events calendar projection updates within a measured freshness objective.
Hands-on exercise · reveal the verification check
Rebuild a derived view after deleting its cache.
Users see accurate facts again from source records.
Resilience: bulkheads, budgets and backpressure
Bound queue length, concurrent work, request deadlines, retries and memory so slow downstream services don't exhaust upstream resources. Implement fail-closed security and degrade only optional features.
A third-party event source outage should not crash the entire public site.
Limit news ingestion to N concurrent fetches, pause on 429, serve last verified headlines with a stale marker.
Hands-on exercise · reveal the verification check
Simulate one dependency taking 30 seconds per call.
Core local content loads and queues remain bounded.
Idempotent cron jobs and overlapping schedules
Scheduled work may retry, overlap or be skipped across deployments. Persist job run IDs, checkpoints and last-success time; use a lock or uniqueness constraint appropriate to single or multi-instance operation.
A periodic importer can duplicate event rows when it runs twice or crashes halfway through.
Hourly scan upserts by verified provider event ID and stores a cursor, allowing safe reruns.
Hands-on exercise · reveal the verification check
Start two copies of the same import simultaneously.
No duplicate rows, and both runs report an intelligible result.
Capacity estimates and failure-domain diagrams
Estimate requests/sec, payload sizes, storage writes, network egress, peak burst, dependencies and recovery targets. Annotate each node with who can fail independently and where data persists.
A system diagram without capacity or failure assumptions isn't an operational architecture.
An event feed with 100k records and 5k daily visitors needs pagination and caching more than six independent services.
Hands-on exercise · reveal the verification check
Estimate request and storage volume for 10× current usage.
Plan identifies which component saturates first and how to measure it.
System-level design
Modular monoliths, bounded contexts and dependency direction
Keep a coherent deployable system while separating clients, bookings, invoicing, notifications and reporting as domain modules. Define allowed dependencies and authoritative data ownership. Extract independent services only when separate scaling, release or ownership clearly justify the added coordination.
A well-structured monolith can offer simpler transactions and debugging than premature microservices.
Let a bookings module write appointments and expose events to a read-only calendar projection.
// Business modules own records; API layers call use cases.
// bookingService.confirm(id) emits BookingConfirmed after commit.Hands-on exercise · reveal the verification check
Sketch module boundaries and allowed dependency arrows.
Every business concept has an authoritative owner.
Transactional outbox, event consumers and deduplication
An outbox writes the business state and a pending event in one database transaction; a publisher then delivers events asynchronously. Consumers need idempotent processing and a plan for late, duplicated and out-of-order messages.
A booking must not disappear from the notification workflow after a crash.
Store BookingConfirmed and an outbox row together; have a worker send confirmation after commit.
BEGIN;
UPDATE bookings SET status='confirmed' WHERE id=42;
INSERT INTO outbox(event_type, aggregate_id) VALUES ('BookingConfirmed',42);
COMMIT;Hands-on exercise · reveal the verification check
Kill the publisher after sending but before acknowledgment.
The retry does not duplicate downstream effects.
Sagas, compensation and cross-service state machines
When a business operation spans systems without a shared transaction, model a saga as explicit steps and compensations. Distinguish actions that can be rolled back from externally visible effects that require follow-up. Define timeouts and a recovery queue for partial completion.
Payment, inventory and scheduling consistency needs a failure policy before scaling.
Reserve an appointment, authorize payment and finalize booking; reverse the reservation if payment fails.
// On failed payment, execute a defined compensating reservation release.
// Record the saga state durably for safe retries.Hands-on exercise · reveal the verification check
List all failures in a three-step workflow.
Each failure leads to a documented recoverable state.
C4 diagrams, ADRs and honest deployed-state documentation
C4 context, container and component diagrams express different levels of architecture; sequence diagrams show one interaction. Architecture Decision Records preserve context, alternatives and trade-offs. Keep these artifacts aligned with source and deployment evidence.
A design diagram is useful only when its status and ownership are clear.
Document the CRM's booking request path and the decision to keep the calendar projection separate from the data owner.
# ADR: choose a modular monolith
# Decision drivers: small team, transactions, deployment simplicity
# Revisit: independent scaling and ownership become essentialHands-on exercise · reveal the verification check
Write a one-page ADR and a sequence diagram.
A reviewer can match each major step to running code.
Resilience: bulkheads, backpressure, health and graceful degradation
Cap per-dependency concurrency, apply deadlines and bounded retries, expose readiness separately from liveness and make optional features fail without disabling unrelated workflows. Cache or queue where stale behavior is acceptable, while critical writes stay authoritative.
A failing map provider should not take down client bookings and invoices.
Show the booking list without travel optimization during a routing provider outage, with an explicit unavailable state.
// Isolate optional provider failure from primary booking read.
try { return await optimizeRoute(); }
catch { return {available:false, stops:savedStops}; }Hands-on exercise · reveal the verification check
Inject routing timeout and database unavailability independently.
Optional outage degrades gracefully; critical failure is visible.
Multi-tenant isolation across workers, caches and reports
Tenant identity must be propagated securely from HTTP auth into background jobs, database queries, cache keys and analytics. Row-level security can enforce additional boundaries when designed correctly. Test negative cases with two valid tenants and long-running workers.
The riskiest leaks often happen outside normal frontend navigation.
Queue a dog-walking reminder with verified tenant context and ensure no other tenant's client record is readable.
ALTER TABLE bookings ENABLE ROW LEVEL SECURITY;
-- Define and test a tenant-scoped policy for this table.Hands-on exercise · reveal the verification check
Run cross-tenant queue and cache tests.
Every cross-tenant attempt is denied and audited.