JS-290 · Lesson 3 of 12 · 27 min
Architecture and technology choices
▶ Video coming soon A video version of this lesson is on the way.
On Tuesday, March 27, the team has a story map, a release line and a list of rules. Now it must decide how the pieces fit together: where the code lives, which programs run where, which data goes in which store, and how the parts talk to each other. These are architecture decisions. They matter more than most code because they are expensive to change later. A function written badly can be rewritten in an afternoon; a decision to keep data in the wrong place can cost a month.
Gareth's advice is to make as few new architecture decisions as possible. The studio already runs a volunteer portal, a partner order service with sign-in and a kitchen board, a mail outbox, a pipeline and monitoring. Every piece Rescue Runs can reuse is a piece that is already tested, already monitored and already understood by Theo at three in the morning. The interesting decisions are the ones where reuse is not obvious, and the team spends the session on those.
Three ways to build it
Mira lays out three options on the whiteboard. The first is to add rescue pages to Theo's PHP application, which already holds volunteers and shifts. The second is to add rescue endpoints to the partner order service, the Node service that handles agencies' orders for Rosa's kitchen. The third is a new, small Node service beside the others, following the same patterns as the partner service but with its own database schema and its own release cycle.
| Option | For | Against |
|---|---|---|
| Extend the PHP application | Volunteer accounts and driver details are already there | The team writes JavaScript; Theo would review every change; PHP releases are slower |
| Extend the partner order service | Same language and patterns; sign-in for outside staff already built | Mixes two unrelated jobs; a rescue bug could take the kitchen board down |
| New Node service beside the others | Separate failures, releases and database permissions; patterns copied, not shared | One more service for Theo to run and monitor |
The team chooses the third option, with conditions from Theo. The new service must use the same deployment pipeline, the same health checks, the same logging format and the same kind of database account as the partner service, so that running it is a copy of something he already does. And it must not share a database schema or tables with anything else; it can read the volunteer data it needs only through the PHP application's existing API.
Architecture decision records
Decisions are easy to make and easy to forget, and six months later nobody remembers why something was done. The studio has used architecture decision records, or ADRs, since JS-260: short documents, one per decision, kept in the repository beside the code. Each has a number, a title, a status, the context that forced a decision, the decision itself and its consequences, good and bad. An ADR is never edited to change its decision; if the team changes its mind, it writes a new ADR that supersedes the old one, so the history stays readable.
# ADR 0003: Drivers sign in with their volunteer portal account
Status: Accepted (2029-03-27)
## Context
Drivers are Food Hub volunteers and already have portal accounts in
Theo's PHP application. Donor staff are not volunteers. We must not
build a new password scheme (Rhea's ground rule, ADR 0001).
## Decision
Drivers and receivers sign in through the portal. The PHP application
issues a short-lived signed token (15 minutes) that the rescue service
verifies, as the partner service does for board devices. Donor staff
use the partner service's sign-in module, copied into this service.
## Consequences
+ No new passwords for 22 drivers; volunteer records stay in one place.
- The rescue service depends on the PHP application being up to sign in.
- Theo must add one endpoint to issue tokens (agreed for Sprint 1).What this code does
An ADR is short enough to read in two minutes and is stored as a Markdown file beside the code it describes. The consequences section lists costs as well as benefits, because an honest record of the trade-off is what lets a later team judge whether the decision still holds. A decision is changed by writing a new ADR that supersedes this one, never by editing it.
The team writes six ADRs in the first week: one for the ground rules, one for the separate service, one for sign-in, one for how updates reach screens, one for storing distances, and one for the offline pickup. Tavish keeps an index so that anyone can see at a glance which decisions stand.
// The ADR index, with superseded records pointing at their replacements.
const adrs = [
{ n: 1, title: 'Ground rules for the capstone', status: 'accepted' },
{ n: 2, title: 'A separate Node service for rescue', status: 'accepted' },
{ n: 3, title: 'Drivers sign in with the portal account', status: 'accepted' },
{ n: 4, title: 'Live updates with server-sent events', status: 'superseded', by: 7 },
{ n: 5, title: 'Store donor locations by area, not address', status: 'accepted' },
{ n: 6, title: 'Offline pickup through the portal outbox', status: 'proposed' },
{ n: 7, title: 'Screens poll every 60 seconds instead', status: 'accepted' },
];
const id = (n) => 'ADR ' + String(n).padStart(4, '0');
for (const a of adrs) {
const note = a.status === 'superseded' ? ` (see ${id(a.by)})` : '';
console.log(`${id(a.n)} ${a.status.padEnd(10)} ${a.title}${note}`);
}
const open = adrs.filter((a) => a.status === 'proposed').map((a) => id(a.n));
console.log('Waiting for a decision:', open.join(', ') || 'none');ADR 0001 accepted Ground rules for the capstone ADR 0002 accepted A separate Node service for rescue ADR 0003 accepted Drivers sign in with the portal account ADR 0004 superseded Live updates with server-sent events (see ADR 0007) ADR 0005 accepted Store donor locations by area, not address ADR 0006 proposed Offline pickup through the portal outbox ADR 0007 accepted Screens poll every 60 seconds instead Waiting for a decision: ADR 0006
What this code does
Each record has a number, a title and a status, and superseded records point to the number that replaced them. Padding the number to four digits keeps the files in order when they are listed alphabetically. The last line picks out proposed records, which are the decisions the team still owes someone.
Live updates or polling?
ADR 0004 and its replacement, ADR 0007, tell a short story. At first Odalys wanted live updates: when a donor posts an offer, drivers' screens should show it at once, using server-sent events like the kitchen board from JS-240. Theo asked a simple question: how quickly does a driver need to know? Lucy's answer was that offers are usually posted two to four hours before pickup, and that a driver noticing within a few minutes is plenty. Live connections would mean another long-lived connection per driver through Theo's web server and another thing to monitor. The team superseded ADR 0004 with ADR 0007: screens ask for changes every 60 seconds while they are visible, and not at all when they are hidden. It is less impressive and much simpler.
This is a common pattern in architecture: the right choice depends on a number that only the users can give. A team that does not ask builds the impressive version by default.
The containers
With the main decisions made, Mira draws the system as containers, in the sense used by the C4 model of software architecture: separately running or separately deployed things, such as a web application, an API service or a database. Each box on the diagram is something Theo could start, stop or back up on its own. Each arrow is a call across a network, and so a place where something can fail or be slow.
| Container | Technology | Runs where | Reused from |
|---|---|---|---|
| Rescue web app | React 19.3, React Router 8, TanStack Query 5, Vite 8 | Static files under /rescue/ on Theo's server, behind the CDN | Portal (JS-220, JS-250) |
| Rescue service | Node 27 LTS, Express 5, zod 4 | systemd service on Theo's server, 127.0.0.1:3200 | Partner service (JS-230, JS-240) |
| Database schema rescue_runs | PostgreSQL 18 | Theo's managed PostgreSQL, role rescue_app, 10 connections | Partner schema pattern |
| PHP application | Theo's existing app | Unchanged, plus one token endpoint | WEB-201 onward |
| Mail outbox | Files Theo's mail queue reads | Theo's server | Reminders script (JS-230) |
Two numbers on the diagram come from Theo's capacity planning. His PostgreSQL server allows 100 connections; his PHP application uses up to 40 and the partner service up to 10, so the rescue service gets 10 as well, leaving room for maintenance and backups. And the service listens only on the local machine, at port 3200, with Theo's web server in front of it handling HTTPS, exactly as the partner service does on port 3100.
One repository, clear folders
Rescue Runs goes into the studio's existing food-hub monorepo, the repository that holds the portal, the partner service, the reminders script, the donation function and the shared riverside-data package. A monorepo means one pull request can change the web app and the API together, the shared package is used directly rather than published, and CI already knows how to build each folder.
food-hub/
apps/
portal/ # volunteer portal (React)
rescue/ # NEW: Rescue Runs web app (React)
services/
partner-orders/ # partner order service (Node)
reminders/ # nightly reminders script (Node)
rescue-runs/ # NEW: Rescue Runs API (Node)
src/
routes/ # HTTP: parse, validate, call a service, map errors
services/ # rules: claiming, receiving, totals
repositories/ # SQL: one module per table group
config.js # start-up configuration, validated
migrations/ # numbered SQL files
test/
functions/donation-webhook/
packages/riverside-data/ # shared helpers (overlap rule, MinHeap, money)
docs/adr/ # decision records for the whole repositoryWhat this code does
The tree shows where the two new folders sit beside the existing ones in the monorepo. Inside the service, code is split into routes, services and repositories, so that HTTP details, business rules and SQL each live in one place. Migrations and tests sit beside the source so that a change to the schema and the tests for it arrive in the same pull request.
Layers and the dependency rule
The folders inside the service are layers, and the team agrees a dependency rule: each layer may use only the layers below it. Routes may call services; services may call repositories; repositories talk to the database. Nothing may call upward. A repository never knows about HTTP status codes, and a route never writes SQL. The rule keeps the claiming logic in one place, where it can be tested without a web server or a database, and it means a change to the database cannot accidentally change the API's error messages.
// Check imports against the dependency rule: routes -> services -> repositories.
const rank = { routes: 3, services: 2, repositories: 1, lib: 0 };
const layerOf = (path) => path.split('/')[1];
const imports = [
['src/routes/runs.js', 'src/services/claims.js'],
['src/services/claims.js', 'src/repositories/runs.js'],
['src/services/claims.js', 'src/lib/overlap.js'],
['src/repositories/runs.js', 'src/routes/errors.js'],
['src/routes/offers.js', 'src/repositories/offers.js'],
];
for (const [from, to] of imports) {
const a = layerOf(from), b = layerOf(to);
const ok = rank[b] < rank[a];
const skips = ok && rank[a] - rank[b] > 1 && b !== 'lib';
const verdict = !ok ? 'VIOLATION' : skips ? 'allowed, but skips a layer' : 'ok';
console.log(`${from} -> ${to}: ${verdict}`);
}src/routes/runs.js -> src/services/claims.js: ok src/services/claims.js -> src/repositories/runs.js: ok src/services/claims.js -> src/lib/overlap.js: ok src/repositories/runs.js -> src/routes/errors.js: VIOLATION src/routes/offers.js -> src/repositories/offers.js: allowed, but skips a layer
What this code does
Each layer gets a rank, and an import is legal only when it points to a lower rank. The repository that imports from routes breaks the rule, so it is reported as a violation. The route that goes straight to a repository is allowed by the strict rule but flagged, because it means business rules may be getting skipped.
Gareth turns this check into a real lint rule later, using the same idea with ESLint's restricted-import settings, so that a violation fails CI rather than waiting for a reviewer to notice. Tests that check the shape of the code rather than its behaviour are sometimes called fitness functions: they keep an architecture from eroding one convenient shortcut at a time.
Sorting runs by distance, without addresses
One of the should-have stories is that drivers see open runs sorted by distance from where they start. That seems to need drivers' home addresses, which the team does not want to collect. ADR 0005 records the solution. Each donor location stores a public business address and its latitude and longitude, which are not personal information. Drivers choose a start area from a short list of neighbourhoods, and each area has a central point. Distances are calculated from that point using the haversine formula, which gives the great-circle distance between two points on a sphere.
Here φ is latitude, λ is longitude, both in radians, and r is the Earth's radius, about 6,371 km. Straight-line distance is not road distance, but for sorting a handful of runs in one city it is close enough, and it needs no outside mapping service and no personal data. The team's example coordinates are invented points, so the numbers below do not describe real places.
// Sort open runs by straight-line distance from a driver's start area.
const R = 6371; // km
const rad = (deg) => (deg * Math.PI) / 180;
function haversine(a, b) {
const dLat = rad(b.lat - a.lat), dLon = rad(b.lon - a.lon);
const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
return 2 * R * Math.asin(Math.sqrt(h));
}
const startArea = { name: 'North End', lat: 44.250, lon: -76.500 };
const runs = [
{ donor: 'Pine Hill Grocers', lat: 44.262, lon: -76.540 },
{ donor: 'Copperleaf Bakery', lat: 44.231, lon: -76.488 },
{ donor: 'Loaf and Ladle', lat: 44.255, lon: -76.505 },
];
const sorted = runs
.map((r) => ({ ...r, km: haversine(startArea, r) }))
.sort((a, b) => a.km - b.km);
for (const r of sorted) console.log(`${r.donor.padEnd(18)} ${r.km.toFixed(1)} km`);Loaf and Ladle 0.7 km Copperleaf Bakery 2.3 km Pine Hill Grocers 3.5 km
What this code does
The haversine function converts the latitude and longitude differences to radians and applies the formula from the lesson, giving kilometres because the radius is in kilometres. Each run gets a distance from the start area's central point, and the list is sorted from nearest to farthest. The coordinates are invented, so the result is a demonstration of the method rather than a map of real places.
The US version of the screen shows miles, converting with 1 mile = 1.609 km, but the service stores and sorts in kilometres everywhere, so the database never mixes units. Choosing one internal unit and converting only at the edges is the same rule the team followed for money in JS-210, where everything is stored in cents.
The stack, pinned
The last part of the session is writing down exact versions, because *React* is not a decision but *React 19.3 with React Router 8* is. The versions match the portal and the partner service, so that Dependabot's weekly updates, set up in JS-210, keep everything moving together.
{
"name": "@food-hub/rescue-runs",
"version": "0.1.0",
"private": true,
"type": "module",
"engines": { "node": ">=27 <28" },
"scripts": {
"start": "node --env-file-if-exists=.env src/server.js",
"test": "node --test",
"lint": "eslint .",
"migrate": "node scripts/migrate.js"
},
"dependencies": {
"express": "^5.2.1",
"pg": "^8.16.0",
"zod": "^4.1.0",
"@food-hub/riverside-data": "workspace:*"
}
}What this code does
The service's package file pins the Node major version with an engines range, the same rule as every other service in the monorepo. Runtime dependencies are kept to four, and the shared riverside-data package is used from the workspace rather than from a registry. The start script loads a local environment file only if one exists, which keeps production settings in Theo's system configuration.
Theo approves the architecture on Thursday, March 29, with one change: the token endpoint in his PHP application will be built first, in the first week of Sprint 1, because everything else depends on it. That dependency goes straight into the plan, which is the subject of lesson 4.
Worked problem
Sharing database connections
Theo's PostgreSQL server allows 100 connections. He keeps 10 for maintenance and backups. The PHP application uses up to 40, the partner service up to 10, and the reminders script up to 2. How many connections are left for the rescue service, and is the planned pool of 10 safe? What if the PHP application is raised to 60?
Show solution
- Already used: 40 + 10 + 2 = 52.
- Available: 100 − 10 − 52 = 38, so a pool of 10 is safe with 28 spare.
- With the PHP application at 60: 60 + 10 + 2 = 72 used, and 100 − 10 − 72 = 18 available.
- A pool of 10 still fits, with 8 spare.
Answer: Today 38 connections are free and the rescue service's 10 leave 28 spare; even if the PHP application grows to 60, 18 are free and 8 remain spare. The numbers go into ADR 0002 so the next service added can check them again.
Common mistakes
MistakeBuilding a new piece of infrastructure because it is interesting.
InsteadReuse what already runs and is monitored unless there is a clear reason not to.
MistakeEditing an old ADR when the decision changes.
InsteadWrite a new ADR that supersedes it, so the history stays readable.
MistakeChoosing live updates without asking how fast users need them.
InsteadAsk the users for the number, then choose the simplest design that meets it.
MistakeLetting repositories return HTTP status codes.
InsteadKeep a dependency rule: routes call services, services call repositories, never upward.
MistakeCollecting home addresses to sort by distance.
InsteadUse start areas with public central points and keep personal data out of the design.
Summary and key terms
- Architecture decisions are expensive to change, so the team makes as few new ones as possible and reuses what already runs.
- Options are compared openly, and each decision is recorded in an ADR with context, decision and consequences; changed decisions are superseded, not edited.
- Asking users for numbers, such as how quickly drivers need to see new offers, often leads to simpler designs such as polling instead of live connections.
- A container diagram shows separately running pieces and the network calls between them.
- Inside the service, layers with a dependency rule keep HTTP, rules and SQL apart, and fitness functions can enforce the rule in CI.
- Distance sorting uses start areas and the haversine formula instead of personal addresses.
- Exact versions are pinned to match the rest of the studio's software.
- Architecture
- The high-level structure of a system: its parts, where they run and how they connect.
- Architecture decision record
- A short document recording one decision, its context and its consequences.
- Superseded
- Replaced by a later decision; the old record stays for history.
- Container (C4 model)
- A separately running or separately deployed part of a system, such as an app, a service or a database.
- Monorepo
- One repository holding several related applications and packages.
- Layer
- A group of code with one responsibility, such as routes, services or repositories.
- Dependency rule
- A rule that each layer may use only the layers below it.
- Fitness function
- An automated check that a system keeps a property of its architecture.
- Haversine formula
- A formula for the great-circle distance between two points given by latitude and longitude.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Why did the team choose a separate service rather than extending the partner service?
Show answer
So that a rescue bug cannot take the kitchen board down, and so that rescue has its own releases and database permissions.
How should a team change a decision recorded in an ADR?
Show answer
Write a new ADR that supersedes the old one.
Why do screens poll every 60 seconds instead of using live connections?
Show answer
Drivers only need to see offers within a few minutes, so polling meets the need with less to run and monitor.
What does the dependency rule forbid?
Show answer
Any layer calling a layer above it, such as a repository using route code.
Try it yourself
Nearest run
Complete nearest(start, runs). Each run has donor, lat and lon; start has lat and lon.
Return the donor name of the run with the smallest haversine distance from start. Use an Earth radius of 6,371 km. Return none for an empty list.
const rad = (d) => (d * Math.PI) / 180;
function haversine(a, b) {
const dLat = rad(b.lat - a.lat), dLon = rad(b.lon - a.lon);
const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;
return 2 * 6371 * Math.asin(Math.sqrt(h));
}
function nearest(start, runs) {
return 'none';
}
const start = { lat: 44.24, lon: -76.52 };
console.log(nearest(start, [
{ donor: 'A', lat: 44.30, lon: -76.40 },
{ donor: 'B', lat: 44.25, lon: -76.51 },
{ donor: 'C', lat: 44.20, lon: -76.60 },
]));
console.log(nearest(start, []));Try it yourself
Layer violations
Complete violations(imports). Each import is [fromPath, toPath], and the layer is the second part of the path, such as routes in src/routes/runs.js.
Ranks are routes 3, services 2, repositories 1. Return the fromPath -> toPath strings for imports that point to the same or a higher rank.
const rank = { routes: 3, services: 2, repositories: 1 };
function violations(imports) {
return [];
}
console.log(violations([
['src/routes/a.js', 'src/services/b.js'],
['src/repositories/c.js', 'src/services/b.js'],
['src/services/b.js', 'src/services/d.js'],
['src/services/b.js', 'src/repositories/c.js'],
]).join('\n'));Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.