M2-S1 — The fleet and the life of a request
Section titled “M2-S1 — The fleet and the life of a request”| Module | M2 — The platform’s architecture and contracts |
| After this session you can | Trace a request from the gateway through the services that handle it, by its correlation id, and explain each hop: routing, identity, tenancy, the answer’s envelope and its errors. |
| Time | Facilitated: 63 min · On your own: 63 min |
| Before you start | M0-S2: Larkspur Lab running, the five windows (workbench). A browser with developer tools (F12). |
| Go deeper | Backend architecture · HTTP API internals · Service topology |
◆ Orientation (1 min) — One save, many hands
Section titled “◆ Orientation (1 min) — One save, many hands”When Omar Haddad marks a work order Urgent and selects Save, the screen answers in a fraction of a second. Behind that answer, the gateway checked who he is and which space he works in, a service checked what he may do, the record was stored with a new version stamp, an event left for the message bus, and within a second another service had matched a reaction and notified the planner on duty. In ACDE you saw these parts as an operator: pods, Services, a gateway, a bus. In this session you see them as an engineer: what each part does with the request, why, and where the evidence of each step is written. This is the map every later engine session hangs on, so the job aid you start today, the engine trace map, grows with each of them.
▤ Concept (13 min) — From the gateway to the stored record
Section titled “▤ Concept (13 min) — From the gateway to the stored record”The fleet, as applications
Section titled “The fleet, as applications”ACDE showed you the deployed shape: twelve applications share combined pods, the rest have pods of their own, and every application keeps its own Kubernetes Service, queue and database whichever pod hosts it (ACDE M1-S1). Hold on to the application as the unit from now on. An application is one service’s code: it owns a slice of the HTTP API, its own queue on the bus, and usually its own database. Where it runs is an operator’s decision; what it does is not.
Most applications are built on LoopBack 4, an open-source TypeScript framework for HTTP APIs. A LoopBack application is organised around a container: a registry in which each piece of the application (a controller, a service class, a repository, a configuration value) is registered under a binding key, and from which each piece receives what it declares it needs. That is the dependency injection you read about in M0-S1, and it is why a Osos service can be extended by adding a file rather than by editing a central list. A few edge applications (identity, storage and the scheduler) are plain Express applications, a smaller Node.js web framework, and follow fewer of these conventions.
| Application | Owns | Why you will meet it |
|---|---|---|
data-service | Modules, entities, records, views, queries, dashboards: the data plane | Almost every request reaches it; it is the hub (M2-S3, M3) |
workflow-service | Running workflows | M4-S3 |
reaction-service | Reactions and their runs | M4-S2 |
indexing-service | Search indexes | M3-S4 |
scheduler-service | Timed and deferred work | M4-S1 |
users-service (the identity server) | Sign-in, tokens, accounts | M5-S1 |
storage-service | Files | M2-S4 |
packaging-service, dependency-service | Packages; the dependency graph you queried in M1-S1 | M6 |
functions-service, integrations-service | Functions; outbound integrations | M6-S1 |
web-socket-service and its peers | Live updates to browsers and phones | M2-S2 |
Applications never import each other’s code. They talk in exactly two ways: synchronously over
HTTP, one service calling another’s API and waiting for the answer; and asynchronously over the
message bus, publishing and receiving messages (M2-S2). Older material describes a third way, a
command sent over the bus with the caller waiting for a reply. On the 1.10 line that is gone: inside
data-service such round trips became direct calls, and between services the HTTP API is the only
request-and-response path. Anything sent over the bus is answered, if at all, by another message
later.
When several applications share one combined pod, a call from one to another can be dispatched
in process, without leaving the pod: the same HTTP request, with the same headers, logs and
errors, handed to the other application’s request handler directly. Nothing about the contract
changes, which is why ACDE could treat in-process dispatch as an operator’s switch. For you it means
one thing when reading logs: two applications in the same pod log under the same pod name, so read
each line’s service field, not the pod prefix, to know which application wrote it.
Inside one application: the shell and its layers
Section titled “Inside one application: the shell and its layers”Every LoopBack application in the fleet has the same skeleton. An application class
(application.ts) builds the container at start-up: it configures the clients for the bus, Redis and
the database, registers the shared components, and sets the base path under which the service’s
routes are mounted. Only data-service mounts at bare /api; every other service mounts at
/api/<service>, such as /api/reaction or /api/dependency. The gateway forwards the path
unchanged, which is why the paths you call are the paths the service declares.
Inside, the code is split into three layers, and the split tells you where to look for what.
- Controllers own HTTP only: the route (
@get('/v2/entities/{entity}/entries')), the binding of parameters and body, and the declarations of who must be authenticated and authorised. They do no business logic. - Services hold the business logic: validating a record, deciding a workflow move, building a query. Many are injected into controllers by binding key.
- Repositories own persistence: reading and writing MongoDB. Because builders create entities at any time, there is no repository class per entity: a factory builds a repository at run time for the collection that holds the entity’s records (M2-S3).
Some kinds of code are found by convention at start-up rather than listed anywhere. A small
family of booters scans named folders for files with a given ending, for example every
*.caster.js file in casters/, and registers each class it finds under a binding key built from
the class’s own declaration. That is how field-type converters, validators, exporters, bus handlers
and background workers join a service. You will only change booted code in the source strand (M8);
everyone else needs to know it exists, because it explains why a feature can appear in a service
without any visible wiring.
The request lifecycle
Section titled “The request lifecycle”A request that reaches a LoopBack service passes through a fixed sequence of steps, each a piece of middleware the service plugs into the framework’s standard chain.
sequenceDiagram participant G as Gateway participant M as Context and logging participant A as Authentication participant I as Interceptors participant C as Controller and services participant R as Send or Reject G->>M: request with identity, space and correlation id M->>A: logging context set (correlation id, space) A->>I: shared key checked, user profile loaded I->>C: parameters parsed, method invoked C-->>R: result, or a typed exception R-->>G: the envelope, or the error body
What to notice: authentication happens inside every service, but it does not check a password or a token. It checks that the request came from the gateway or another service, and then trusts the identity they forwarded.
- Context. The correlation id and the space id are read from the request’s headers and put into the logging context, so every line this request causes carries them. The tenant’s languages are loaded (from Redis, falling back to the database).
- Authentication. The service checks the shared key header. The gateway adds it to every
request it forwards, and services add it when they call each other; ACDE taught you to keep it
identical everywhere (ACDE M3-S2). Here is why it matters:
with the right key present, the service reads the caller’s identity from headers the gateway set,
chiefly
x-user-id(the person or application user),x-client-id(the program that obtained the token) and, when someone acts for a colleague, the delegation headers. It then loads that user’s profile: their groups, levels and grants, the raw material of every access decision. - Interceptors. Pluggable checks that may stop a request before the controller runs, for example refusing a delegated request that the delegation does not cover.
- The controller method runs, calling services and repositories. Access is decided at this point, per object, by the permission engine you open in M5-S2.
- Send or reject. The result is shaped into the response (next section).
Where identity is established, and where it is trusted
Section titled “Where identity is established, and where it is trusted”This is the platform’s trust model, and you will rely on it in every security discussion of the course. Identity is established once, at the edge: the gateway validates the caller’s token or application token and works out the space from the host. Identity is trusted everywhere else: services do not re-validate tokens; they accept the identity headers that arrive with a valid shared key. Two design consequences follow.
- The gateway owns those headers. It removes any copy a caller sends of the headers it sets (the shared key, the identity of the caller, the service name, the space) and writes its own. A client therefore cannot claim to be someone else by adding a header, and a well-behaved client never sets them.
- Services must be unreachable except through the gateway. A service trusts whatever arrives with the shared key, so anything that can reach a service directly and holds the key is trusted completely. That is why ACDE kept the services behind the gateway and the key in a Secret, and why the dev documentation tells integrators never to call a service port. In M5-S4 you treat this boundary as one of the trust boundaries of your threat model.
How a request finds its tenant and space
Section titled “How a request finds its tenant and space”A tenant is one organisation’s isolated installation; a space is a working area inside it (ACSA, ACE). ACDE showed that the gateway resolves the request’s host name to a domain and a space, and refuses unknown hosts (ACDE M3-S2). What happens next is the 1.10 multi-tenancy runtime.
The gateway stamps the space on the request as x-space-id (discarding any value the client sent).
In the service, a space scope is opened for the request’s whole asynchronous tree: whatever runs
because of this request, however many awaits deep, can ask “which space am I in?” and get the same
answer. The tenant works the same way, in a tenant scope. Every database access resolves the
tenant and space at the connector, the last step before MongoDB, so no query written anywhere in
the code can forget to scope itself. And the scope travels: an outbound service call carries
x-space-id from it, and every message published on the bus carries the space and the tenant, so the
service that receives the message minutes later re-enters the same scope.
When the scope is missing, the platform refuses rather than guesses. A service reached without a
usable space answers 400 SPACE_CONTEXT_MISSING; a bus message without a space is dead-lettered at
once without running its handler. (Through the gateway neither happens, because the host always
supplies the space.) A single-tenant installation such as Larkspur’s is simply a cell of one
tenant: the same machinery, with the one tenant set by configuration.
flowchart LR H["Host name"] -->|"gateway resolves"| S["space (x-space-id)"] S --> RS["request scope<br/>tenant + space"] RS --> DB["every database call<br/>scoped at the connector"] RS --> HTTP["outbound service calls<br/>carry x-space-id"] RS --> BUS["bus messages<br/>carry space and tenant"] BUS --> RS2["receiving service<br/>re-enters the same scope"]
What to notice: the space is decided once, from the host, and then carried. Nothing downstream asks the caller again, which is why the host name a client uses is the tenant it works in.
The answer: envelope, errors and conflicts
Section titled “The answer: envelope, errors and conflicts”ACE taught you the answer’s shape: {"success": true, "result": …}, or {"success": false, "error": {…}}, with /v3 reads returned bare (ACE M5-S1). Here is how it
is made. A single send step, shared by every LoopBack service, wraps every successful result in
the envelope; on the 1.10 line it leaves a GET on a /v3/ path bare, because external
integrations read those bodies directly. A single reject step turns every exception into the
error body: the exception carries a stable code (such as ENTITY_NOT_EXIST or
UPDATE_CONFLICT) and an HTTP status; the message is looked up in the service’s error dictionary in
both languages (if the code is missing from the dictionary, the code itself becomes the English
message); serviceName names the service that raised it; and traceId is the correlation id. When
one service calls another and gets a 4xx, it answers with that service’s own status and body rather
than flattening it to 500, so serviceName tells you where a refusal really came from.
Optimistic concurrency protects against two people saving the same thing at once. Definitions
(entities, views, queries) and, on the 1.10 line, records carry an updateIdentifier: a change token
renewed on every write. A client that read a record sends the token back with its update; if the
stored token has moved on, someone else saved in between, and the answer is 409 UPDATE_CONFLICT
instead of a silent overwrite. A record that has no token yet is never refused on that account: the
token is stamped on its next write and guards it from then on.
▶ Guided demo (10 min) — Follow Omar’s save
Section titled “▶ Guided demo (10 min) — Follow Omar’s save”In Larkspur Lab, as Rami Aziz, with the logs window and the record store ready.
-
Open Asset Maintenance › Work Orders and open Inspect bearing noise on C-201. Open the browser’s developer tools on the Network tab.
-
Set Priority to Urgent and select Save. In the Network tab, select the request that saved it (a
PATCHorPUTunder/api/) and copy thex-correlation-idfrom its response headers.Screenshot pending The browser's Network tab after saving a work order, with the save request selected and its response headers showing the correlation id What to notice: the id was created by the gateway, not by the browser; every service that touches this save will log it.
-
Search every pod’s log for it, keeping only the fields that matter:
Terminal window ID=<the id>kubectl -n larkspur logs -l app.kubernetes.io/instance=lk --all-containers --prefix --since=10m \--max-log-requests=30 | grep "$ID" | sed 's/^\[\([^]]*\)\] /\1 /' | cut -c1-220 -
Read the lines in time order. First the gateway’s access line, then
data-service’s lines for the update (the request lifecycle: context, the write). Then lines from other applications, a fraction of a second later, all carrying the same id: the reaction application matching Notify planner of urgent work order, the indexing application updating search, the timeline recording the change. Those arrived over the bus, carrying the id inside the message. -
In the record store, read the work order’s stamp:
db.work_orders.findOne({"value.title": /C-201/}, {updateIdentifier:1, updateInfo:1}). ItsupdateInfo.doneAtis your save’s time; itsupdateIdentifieris the token the next writer must present. -
In the portal, the notification bell of Omar Haddad (sign in as
omar.haddadin a private window) shows the notification the reaction sent.
The demo shows the shape you will draw in the lab: one HTTP request handled by one service, and the work that follows travelling over the bus to several.
✓ Practice (5 min) — Check the model
Section titled “✓ Practice (5 min) — Check the model”A service receives a request with a valid shared key and x-user-id set to Sara Qasim’s id. What has
the service checked about Sara?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
An error body says "serviceName": "Reaction Service" for a call you sent to data-service. What
does that tell you?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
A team calls data-service directly, inside the cluster, without an x-space-id header. The service
runs with enforcement on. What happens?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
A colleague’s design has data-service send a command over the bus to the workflow service and wait
for the reply before answering the user. What do you tell them about the 1.10 line?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
⛏ Lab (24 min) — Trace three requests
Section titled “⛏ Lab (24 min) — Trace three requests”Goal. Three requests traced by correlation id through Larkspur Lab, a read, a write that fires a reaction, and a refusal, each with its hop sequence drawn and its evidence quoted.
Before you start. Larkspur Lab; BASE and TOKEN set; the logs window ready
(workbench). A file m2-s1-traces.md. The tap is not needed.
Request 1: a read
-
Read the open work orders with your own correlation id:
Terminal window curl -s -D - -H "x-app-token: $TOKEN" -H "x-correlation-id: lk-m2s1-read" \"$BASE/api/v2/entities/work_orders/entries?filterCriteria=%7B%22limit%22%3A5%7D" -o read.jsonjq '.success, (.result | keys)' read.json -
Find
lk-m2s1-readin every pod’s log (workbench, the logs window). Record which applications logged it and how many lines each. -
In
m2-s1-traces.md, draw the hops: caller, gateway,data-service, MongoDB, and back.
Request 2: a write that fires a reaction
- In the portal, as Rami Aziz, open Lubricate bearings on P-102 and set Priority to Urgent. Save, and copy the correlation id from the save’s response headers, as in the demo.
- Find the id in every pod’s log. Sort the lines into those from the HTTP request and those from handling a bus message (the application name and the message text tell you).
- Read the work order’s
updateIdentifierandupdateInfo.doneAtin the record store. - Draw the hops: the synchronous part (caller, gateway,
data-service, MongoDB) and the asynchronous part (the bus, then each application that received the event, and what it did).
Request 3: a refusal, twice
-
Ask for an entity that does not exist (the singular is a deliberate mistake):
Terminal window curl -s -H "x-app-token: $TOKEN" -H "x-correlation-id: lk-m2s1-refused" \"$BASE/api/v2/entities/work_order/entries" | jq '{success, error: .error.code, count: (.result | length?)}' -
Find
lk-m2s1-refusedin the logs. Note which applications logged it. -
Now send a read with a wrong token: repeat step 8 with
-H "x-app-token: not-a-token"and the correlation idlk-m2s1-badtoken, on the correct entitywork_orders. -
Find
lk-m2s1-badtokenin the logs and note which applications logged it. -
Draw both refusals’ hops, and mark where each one stopped.
-
Under the three drawings, write one sentence for each request saying which concept section explains its shape.
Check.
- For request 1, the gateway and
data-servicelogged your id, and you drew the round trip. - For request 2, you found lines from the HTTP request and from at least two applications that
received the bus event, and you quoted the record’s new
updateIdentifier. - For request 3, you recorded the error
code,serviceNameandtraceIdof the unknown entity, and thetraceIdequals your correlation id. - You showed that the wrong-token request stopped at the gateway: no service logged its id.
- Four drawings, each with the point where the request ended.
Pass condition. All five checks hold.
If something goes wrong
| What you see | What to do |
|---|---|
Request 1 answers 401 | TOKEN is not set in this terminal, or was mistyped. echo ${#TOKEN} should print a length, not 0. |
Request 2’s id appears only in the gateway and data-service | The bus work may take a second or two; search again. If still nothing, check the reaction Notify planner of urgent work order is active on Work Orders › Reactions. |
| No reaction line at all, ever | The reaction application’s pod may be unready: kubectl -n larkspur get pods. In the combined pod, look for the reaction application’s name inside the core-rest pod’s lines. |
Request 3 answers 404 with an HTML body | You called a path the ingress does not route. Check the /api/ prefix. |
The wrong-token id appears in data-service | Your token variable is still being sent: the -H with not-a-token must replace it, not be added beside it. |
Model answer
Request 1. Logged by the gateway (one access line) and by data-service (the request’s lines),
nothing else. Hops: caller → gateway (token checked, space from the host, id kept) → data-service
(shared key checked, profile loaded, query run) → MongoDB → data-service (send step wraps the
result) → caller. The answer is true and result holds the records: a v2 read is enveloped.
Request 2. Synchronous: gateway → data-service: the update is validated, written with a new
updateIdentifier and updateInfo (Rami Aziz, the save’s time), and an event is published.
Asynchronous, with the same id: the reaction application matches Notify planner of urgent work
order and the notification application sends Omar’s notification; the indexing application updates
the work order’s search entry; the timeline application records the change. Each of those is a
separate consumer of the event, with its own queue (M2-S2 opens them up).
Request 3, unknown entity. With the workbench credential there is no error body: the answer is
success: true with an empty list, because the data service checks the caller’s grants on that name
before it looks the entity up, and finds none (the known issue in M0-S2). A
caller with Edit at system level gets code: "ENTITY_NOT_EXIST" (404), serviceName data-service
and traceId: "lk-m2s1-refused". Either way it is logged by the gateway and data-service: the request
passed the gateway (the token was valid), and the data service answered it.
Request 3, wrong token. A 401 from the gateway (AUTHENTICATION_ERROR), logged by the gateway
only: no service saw it, because identity is established at the edge and a request without one is
never forwarded.
The four shapes. A read is one round trip; a write is a round trip plus a fan-out over the bus; a refusal by a service has the full inbound path and an error body built by the service; a refusal at the gateway never enters the fleet.
◇ Worked scenario (3 min) — “Let us call the data service directly”
Section titled “◇ Worked scenario (3 min) — “Let us call the data service directly””Larkspur’s telemetry contractor proposes a shortcut for the condition-monitoring feed you will build
in M7: their collector will run as a pod inside the cluster and post readings straight to
data-service’s internal address, “skipping the gateway to save latency and an authentication
round trip”. They ask for the shared key. Decide at each point before you read on.
Decision 1: what would the collector have to send?
Walk the request lifecycle. Without the gateway, nothing adds the shared key, the identity or the space. So the collector would have to send all three itself: the shared key, a user id to act as, and the space id. Each is something only the gateway is meant to set.
Decision 2: what would that give the collector?
The service trusts any request that carries the shared key, and it builds the caller’s profile from the user id it is given. A process holding the key can therefore act as any user in any space. The contractor asked for a sensor feed and would receive the platform’s master key. That breaks the trust model at its root: identity is established at the edge precisely so that no one else has to be trusted with it.
Decision 3: is there a cost worth saving?
Measure before you argue. The gateway adds a token check (cached for minutes, ACDE M3-S2) and one hop inside the cluster: a few milliseconds per request. A reading arrives every few seconds per sensor. The saving is real but irrelevant to the feed, and it is paid for with the whole platform’s trust.
Decision 4: what do you offer instead?
The documented path: the collector calls the API through the gateway with its own application user’s token, holding only the rights it needs (create readings, nothing else), from the host of the right space. If latency ever matters, the answer is batching readings, not bypassing the edge. You write a decision record (M1-S2), because the request will come back.
The outcome. The contractor gets an application user and a token the same day. The shared key stays where ACDE put it: in a Secret that only the platform’s own pods read.
✓ Practice (6 min) — Read the evidence
Section titled “✓ Practice (6 min) — Read the evidence”Two planners edit the same work order. Ana saves first. Ben, whose screen still holds the version he read before Ana’s save, saves a minute later. On the 1.10 line, what does Ben’s client receive, and why?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
In request 2’s logs, the reaction application’s line appears 300 milliseconds after data-service
answered the browser. Why after, and not before?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
An integrator sends x-user-id set to Leila Amari’s id with every call, hoping to act as her. What
happens?
Check your answer
The correct answer is B. Open the explanation under each option to see why.
A new field-type converter appears in data-service after an upgrade, but nobody added it to any list
in the code. How did the service find it?
Check your answer
The correct answer is C. Open the explanation under each option to see why.
A bus message reaches the indexing application without a space on it. What does the 1.10 runtime do?
Check your answer
The correct answer is A. Open the explanation under each option to see why.
↺ Recap (1 min) — The map you will hang everything on
Section titled “↺ Recap (1 min) — The map you will hang everything on”You can now describe the fleet as applications that talk over HTTP and the bus, follow a request through a service’s lifecycle, explain where identity is established and where it is trusted, show how the space travels into every database call and message, and read an answer or an error for what it says about where it was made.
Next. M2-S2 opens the asynchronous half you saw fan out in request 2: the messages themselves, what they carry, who receives them, and what happens when a receiver fails.