How care works

Week 1 · ~10 h

Health data is a by-product of clinical work. Nobody in a hospital types data for its own sake: a registration clerk types a name so the wristband prints, a nurse records a blood pressure because the next nurse needs it, a physician signs an order because the lab won't run a test without one. Every field you will query in this course was written by a person doing a job, at a particular moment, under time pressure. Know who records what, and when, or you will misread timestamps, statuses and identifiers in every later week.

The mistakes reach patients. Stamp every event with the visit's start time, and an antibiotic seems to come before the test that justified it. Assume one medical record number per person, and one patient becomes two half-records, one of which holds the allergy.

This lecture walks one patient through one emergency visit, from the front desk to the bill. We generate synthetic patients with Synthea, pick one emergency encounter, and use jq to find every FHIR resource that belongs to it: what was recorded, by whom, and when. Then we write the visit down twice, as a nurse would tell it and as a timeline that ties each sentence to a FHIR resource and field. That pair is your build for the week.

Done when

This week you build a nurse's account of one encounter, a timeline that backs it up, and the start of a glossary. The numbered steps are under Your build this week. You are done when:

The patient journey

Most hospital visits follow the same eight steps, whatever the reason for the visit. Each step is done by a different person, and each leaves a different kind of record behind.

  1. Registration. A clerk finds or creates the patient's record, checks identity and insurance, and opens a visit. Medical record numbers, and duplicates, are born here.
  2. Triage. A nurse decides how urgent the patient is and takes vital signs.
  3. Orders. A physician or nurse practitioner orders tests and medications. An order is a request: it names what should happen.
  4. Results. A specimen is collected, the lab runs the test, and results are verified and reviewed.
  5. Notes. Clinicians write what they found and decided.
  6. Discharge. The patient goes home with prescriptions, or is admitted or transferred.
  7. Coding. Coders read the record and assign standard diagnosis and procedure codes.
  8. Billing. Codes become a claim to an insurer or provincial plan, and a payment or denial comes back.

Here is the same journey from the data's point of view: who usually records each step, and where it lands in FHIR R4. The rest of this lecture checks each row against real (synthetic) data.

StepUsually recorded byLands in FHIR R4
RegistrationRegistration clerkPatient.identifier, Encounter.class, Encounter.period.start
TriageTriage nurseObservation (vital signs, triage score), Encounter.status
OrdersPhysician, nurse practitionerServiceRequest, MedicationRequest.requester
ResultsNurse (specimen), lab, ordering clinicianObservation, DiagnosticReport
NotesPhysician, nurseDocumentReference, Condition, Procedure
DischargePhysician, nurse, clerkEncounter.period.end, Encounter.status, MedicationRequest
CodingHealth information (coding) staffClaim.diagnosis, Claim.item
BillingBilling staff, insurer or provincial planClaim, ExplanationOfBenefit

Clerks, nurses, physicians, pharmacists, lab staff, coders and billing staff all write to the same record, and access follows role: a clerk can change an address but not a diagnosis, a coder can read the chart but not change it. In FHIR the person shows up as a reference in fields like performer, requester or author. When those are empty, as they often are in Synthea, “who said this?” has no answer in the data.

Generating a small population

Synthea simulates whole lives (illnesses, visits, medications, insurance) and exports each person as a FHIR bundle. It is a single jar, copied into our work directory:

$ java -version 2>&1 | head -1
openjdk version "25.0.4.1" 2026-08-18
$ jq --version
jq-1.7
$ java -jar synthea-with-dependencies.jar \
    -p 10 -s 42 -cs 42 -r 20261031 \
    --exporter.fhir.use_us_core_ig=false 2>&1 \
  | grep -e ' -- ' -e Records
9 -- Jody426 Hickle134 (8 y/o M) Newburyport, Massachusetts  (11454)
2 -- Wilfredo622 Fritsch593 (15 y/o M) Whitman, Massachusetts  (20437)
7 -- Wallace647 Effertz744 (16 y/o M) Revere, Massachusetts  (22632)
8 -- Lindsay928 Zieme486 (19 y/o F) Worcester, Massachusetts  (25223)
3 -- Ezekiel373 Walter473 (27 y/o M) Watertown, Massachusetts  (37347)
4 -- Shalanda398 Kelsie51 Jenkins714 (30 y/o F) Lowell, Massachusetts  (42162)
10 -- Cristobal567 Montero62 (79 y/o M) Saugus, Massachusetts  (109553)
5 -- Jona712 Bonnie873 Gibson10 (67 y/o F) Peabody, Massachusetts  (99777)
6 -- Tennille443 Denna536 Trantow673 (66 y/o F) Arlington, Massachusetts  (92068)
1 -- Corie618 Sofia418 Beahan375 (101 y/o F) Franklin, Massachusetts  (153177)
Records: total=10, alive=10, dead=0
$ ls output/fhir | wc -l
12

-p 10 asks for ten living patients and -s 42 seeds the population. -cs 42 seeds the clinician generator and -r 20261031 fixes the reference date that ages are computed from; without them each run uses the current time. The 12 files are one per patient plus two describing hospitals and practitioners.

Tested: with -s 42 and a fixed date, two runs gave the same ten people but different clinician names, and leaving out -r moved a birth date by a day. Adding -cs 42 -r 20261031 made the patient files byte-for-byte identical; only the hospital and practitioner file names, which carry a timestamp, changed.

Each file is a FHIR Bundle whose entry array holds every resource for that person. Counting resource types is the first thing to do with any bundle. We'll follow Lindsay928 Zieme486, 19, from Worcester (the digits are Synthea's, so nobody mistakes her for a real person):

$ p=$(ls output/fhir/Lindsay928_*.json)
$ jq -r '.entry[].resource.resourceType' $p \
  | sort | uniq -c | sort -rn
    183 Observation
     92 Procedure
     39 ExplanationOfBenefit
     39 Claim
     30 Encounter
     29 Condition
     17 Immunization
     17 DiagnosticReport
     12 SupplyDelivery
      9 MedicationRequest
      5 CareTeam
      5 CarePlan
      2 MedicationAdministration
      2 ImagingStudy
      2 Device
      1 Patient

Observations dominate, as in real records: every vital sign and lab value is its own Observation. Then come Procedures, Claims with their ExplanationOfBenefit twins, and one Encounter per visit.

Something is missing, though: there are no notes. There is no DocumentReference in this list. That is a side effect of the flag we used. --exporter.fhir.use_us_core_ig=false gives plain FHIR R4, which week 0 needed, but on this Synthea build it also turns off clinical notes. This week we need the notes, so run it again without the flag, into a separate directory:

$ java -jar synthea-with-dependencies.jar \
    -p 10 -s 42 -cs 42 -r 20261031 --exporter.baseDirectory=./uscore/ 2>&1 \
  | grep Records
Records: total=10, alive=10, dead=0
$ cp uscore/fhir/Lindsay928_*.json lindsay.json
$ jq -r '.entry[].resource.resourceType' lindsay.json \
  | sort | uniq -c | sort -rn | head -8
    183 Observation
     92 Procedure
     47 DiagnosticReport
     39 ExplanationOfBenefit
     39 Claim
     30 Encounter
     30 DocumentReference
     29 Condition

Same people, plus 30 DocumentReferences: one clinical note per encounter. The 30 extra DiagnosticReports are the same notes wrapped as reports. From here on we use this file, copied to lindsay.json.

Tested: resource counts change between Synthea builds; an older build gave different numbers. Never hard-code them in a test.

Encounters

An Encounter is one interaction between a patient and a provider: a clinic appointment, an emergency visit, a hospital stay, a video call. Two fields tell you what kind of encounter you're looking at and where it is in its life.

Encounter.class is the setting, coded from HL7's ActEncounterCode list: AMB ambulatory (outpatient), EMER emergency, IMP inpatient, HH home health, VR virtual, and a few more. Inpatient means the patient was admitted to a bed; an emergency visit can end in discharge home or in an admission, which starts a new inpatient encounter. Encounter.status is the lifecycle state: planned, arrived, triaged, in-progress, onleave, finished, cancelled, entered-in-error or unknown. Count them across all ten patients:

$ jq -r '.entry[].resource
  | select(.resourceType == "Encounter")
  | "\(.class.code) \(.status)"' uscore/fhir/[A-Z]*.json \
  | sort | uniq -c | sort -rn
    522 AMB finished
     22 EMER finished
     15 IMP finished
     10 VR finished
      2 HH finished

Mostly ambulatory, as in life. And every encounter is finished, because Synthea writes the record after the simulation ends. In a live system an emergency encounter moves through arrived, triaged and in-progress, and a query at 12:15 sees a different status from one at 15:00. FHIR keeps the history in Encounter.statusHistory, if anyone fills it in.

Lindsay has two emergency visits and no inpatient stays. We take the second and save its id in enc:

$ jq -r '.entry[].resource
  | select(.resourceType == "Encounter")
  | select(.class.code == "EMER" or .class.code == "IMP")
  | [.class.code, .period.start[0:16],
     .reasonCode[0].coding[0].display] | @tsv' lindsay.json
EMER	2020-02-19T01:51	Sprain (morphologic abnormality)
EMER	2023-03-19T11:55	Acute infective cystitis (disorder)
$ enc=$(jq -r '.entry[].resource
  | select(.resourceType == "Encounter")
  | select(.period.start | startswith("2023-03-19"))
  | .id' lindsay.json)
$ echo $enc
46976cf7-b0bf-be20-0135-e424294d3c62

Every terminal below starts with enc set to that id. Here is the Encounter itself, trimmed to the fields we care about:

$ jq --arg enc $enc '.entry[].resource | select(.id == $enc)
  | {class: .class.code, status, statusHistory, period,
     type: .type[0].text,
     reason: .reasonCode[0].coding[0].display,
     who: .participant[0].individual.display}' lindsay.json
{
  "class": "EMER",
  "status": "finished",
  "statusHistory": null,
  "period": {
    "start": "2023-03-19T11:55:36-04:00",
    "end": "2023-03-19T14:19:32-04:00"
  },
  "type": "Encounter for symptom (procedure)",
  "reason": "Acute infective cystitis (disorder)",
  "who": "Dr. Angele108 Bogan287"
}

A visit of just under two and a half hours for acute infective cystitis, a bladder infection (see MedlinePlus if, like most engineers, you need the clinical term explained). One practitioner is listed. statusHistory is empty, as expected.

ADT events: the messages that announce the workflow

Synthea hands us the finished record. A hospital's systems learn about the visit while it happens, from ADT (admit, discharge, transfer) messages in HL7 version 2 that registration sends at each step. Week 3 (HL7 v2 + patient identity) takes these messages apart byte by byte; this week, just learn the five you'll meet most and what each one would change in FHIR:

EventHL7 v2 nameWhat happenedTypical FHIR effect
A04Register a patientClerk registers an outpatient or emergency arrivalEncounter created, class EMER or AMB, status arrived
A01Admit/visit notificationPatient admitted to a bedEncounter with class IMP, status in-progress, location
A02Transfer a patientPatient moves to another unit, room or bedNew Encounter.location entry; the old one gets an end time
A03Discharge/end visitPatient leavesstatus finished, period.end, hospitalization.dischargeDisposition
A08Update patient informationClerk corrects or adds detailsPatient or Encounter fields updated; no new encounter

For Lindsay's visit, a typical feed would carry an A04 when she was registered at 11:55, perhaps an A08 if the clerk fixed her phone number while she waited, and an A03 when she left at 14:19. Had she been admitted, an A01 would have opened an inpatient encounter, and every move between units would have sent an A02. Exactly which events a site sends, and with which fields filled in, is written in each interface's specification; the HL7 v2-to-FHIR project publishes suggested mappings.

Everything that points at the encounter

The Encounter is the hub, but it doesn't list its spokes: the Observations, Procedures and the rest each carry a reference to the encounter. Inside a Synthea bundle, references use the urn:uuid: form of the target's id, so a blunt but effective way to find everything that mentions our visit is to turn each resource into a string and search it:

$ jq -r --arg ref "urn:uuid:$enc" '.entry[].resource
  | select(tostring | contains($ref)) | .resourceType' \
  lindsay.json | sort | uniq -c | sort -rn
     21 Observation
     10 Procedure
      2 ExplanationOfBenefit
      2 DiagnosticReport
      2 Claim
      1 Provenance
      1 MedicationRequest
      1 DocumentReference

Forty resources. The Claims and EOBs point at the encounter from inside their item lists, which is why we searched whole resources. The Provenance isn't really about this visit: it lists every resource in the bundle. String search is fine for exploring; in code, follow named fields such as Observation.encounter.

Now sort them by time. Every resource has its own time field, and they have different names: Observation.effectiveDateTime, Procedure.performedPeriod.start, MedicationRequest.authoredOn, DocumentReference.date, Claim.created. This filter (download timeline.jq) picks the first one each resource has, groups rows that share a minute and a field, and prints the count:

# Every resource in a Synthea bundle that points at one
# encounter, sorted by its own clinical time.
# Usage: jq -r --arg enc ENCOUNTER_ID -f timeline.jq BUNDLE
# Prints: time  count  Resource.field  what (+N more kinds)

# The field that says when this resource happened.
def when:
  [ ["effectiveDateTime", .effectiveDateTime],
    ["performedPeriod.start", .performedPeriod.start],
    ["authoredOn", .authoredOn],
    ["date", .date],
    ["created", .created] ]
  | map(select(.[1] != null)) | first;

def what:
  (.code.text // .code.coding[0].display
   // .medicationCodeableConcept.text
   // .category[0].coding[0].code // .type.coding[0].code
   // "")
  | sub(" \\([a-z/ ]+\\)$"; "");

def rows:
  if .resourceType == "Encounter" then
    [.period.start, "Encounter.period.start", .class.code],
    [.period.end, "Encounter.period.end", .status]
  else
    when as $w | [$w[1], .resourceType + "." + $w[0], what]
  end;

("urn:uuid:" + $enc) as $ref
| [ .entry[].resource
    # Provenance lists every resource in the bundle; skip it.
    | select(.resourceType != "Provenance")
    | select(.id == $enc or (tostring | contains($ref)))
    | rows ]
| group_by(.[0][0:16] + .[1])
| sort_by(.[0][0])
| .[]
| (map(.[2]) | unique) as $w
| "\(.[0][0][11:16])  \(length)  \(.[0][1])  \($w[0][0:22])"
  + (if ($w | length) > 1 then " +\($w | length - 1)" else "" end)
$ jq -r --arg enc $enc -f timeline.jq lindsay.json
11:55  1  DiagnosticReport.effectiveDateTime  History and physical n
11:55  1  Encounter.period.start  EMER
11:55  1  Procedure.performedPeriod.start  History taking
11:55  1  DocumentReference.date  clinical-note
12:04  1  Procedure.performedPeriod.start  Discussion about signs
12:10  1  Procedure.performedPeriod.start  Triage: emergency cent
12:25  1  Procedure.performedPeriod.start  Taking patient vital s
12:30  6  Observation.effectiveDateTime  Blood Pressure panel w +5
12:30  1  Procedure.performedPeriod.start  History and physical e
13:29  1  Procedure.performedPeriod.start  Urinalysis with reflex
13:39  1  Procedure.performedPeriod.start  Urine specimen collect
13:49  1  Procedure.performedPeriod.start  Urinalysis with reflex
13:59  1  DiagnosticReport.effectiveDateTime  Urinalysis macro (dips
13:59  15  Observation.effectiveDateTime  Bacteria [#/area] in U +14
13:59  1  Procedure.performedPeriod.start  Antibiotic therapy
14:09  1  MedicationRequest.authoredOn  nitrofurantoin, macroc
14:09  1  Procedure.performedPeriod.start  Patient discharge
14:19  2  Claim.created  institutional +1
14:19  1  Encounter.period.end  finished
14:19  2  ExplanationOfBenefit.created  institutional +1

The encounter start is not the time of everything in it

Read the left column. The encounter started at 11:55, but triage happened at 12:10, the urine sample was collected at 13:39, the results were recorded at 13:59 and the prescription was written at 14:09. If a dashboard stamps every event with the encounter's start time, the antibiotic appears to have been chosen more than two hours before there was any evidence for it, and a report of “time from arrival to antibiotic” comes out as zero. For an inpatient stay the error is days, not hours.

Don't use the encounter's start time as the time of every event in it. The rule: use the time field of the resource that describes the event, and treat Encounter.period as the frame around them. When a resource has no time of its own, say so in your analysis rather than borrowing the encounter's.

The timeline also shows that charting lags the care. Triage starts at 12:10 and vitals are taken at 12:25, but the six Observations holding the triage score and vital signs are stamped 12:30. In real data the gaps are bigger, and some charting happens after the patient has left.

Orders, specimens and results

In a real hospital, the lab half of the journey has distinct moments: a physician orders a urinalysis (in FHIR, a ServiceRequest), a nurse collects the specimen (a Specimen with its collection time), the lab receives and runs it, results are verified and released, and the ordering clinician reviews them. In FHIR the results land as Observations, grouped under a DiagnosticReport that points back to the order through basedOn. Let's see what Synthea kept:

$ jq --arg ref "urn:uuid:$enc" '.entry[].resource
  | select(.resourceType == "DiagnosticReport")
  | select(.encounter.reference == $ref)
  | {code: .code.coding[0].display, status,
     effectiveDateTime, issued, results: (.result | length),
     performer: .performer[0].display}' lindsay.json
{
  "code": "Urinalysis macro (dipstick) panel - Urine",
  "status": "final",
  "effectiveDateTime": "2023-03-19T13:59:32-04:00",
  "issued": "2023-03-19T13:59:32.082-04:00",
  "results": 14,
  "performer": "COMFORT HOME CARE, LLC"
}
{
  "code": "History and physical note",
  "status": "final",
  "effectiveDateTime": "2023-03-19T11:55:36-04:00",
  "issued": "2023-03-19T11:55:36.082-04:00",
  "results": 0,
  "performer": "Dr. Angele108 Bogan287"
}
$ jq -r --arg ref "urn:uuid:$enc" '.entry[].resource
  | select(.resourceType == "Observation")
  | select(.encounter.reference == $ref)
  | select(.code.text | test("severity|Nitrite|Leukocyte est"))
  | [.effectiveDateTime[11:19], .issued[11:23],
     .code.text[0:30], .valueCodeableConcept.text] | @tsv' \
  lindsay.json
12:30:22	12:30:22.082	Emergency severity index [ESI]	Needs 1 resource
13:59:32	13:59:32.082	Nitrite [Presence] in Urine by	Nitrite detected in urine (finding)
13:59:32	13:59:32.082	Leukocyte esterase [Presence] 	Urine leukocyte test one plus (finding)

Two reports. The urinalysis groups 14 result Observations; the other report is the clinical note again. The fields to understand are effectiveDateTime and issued. FHIR defines Observation's effective as the “physiologically relevant time”, usually the time of the procedure or of specimen collection, and the report's issued as the time this version of the report was made available, typically after review and verification. In real data, issued is minutes to days after effective, and the gap is the turnaround time that lab managers watch.

Synthea collapses all of that: issued is 82 milliseconds after effective, and effective is the result time (13:59), not the collection time (13:39, which exists only as a Procedure). The bundle has no ServiceRequest or Specimen at all, so the order exists only as the “Urinalysis with reflex…” Procedures. Learn the shape from Synthea, not the lab timing.

The first line is the triage score charted at 12:30, on the Emergency Severity Index, a five-level triage scale that sorts less urgent patients by how many resources (tests, imaging, IV fluids) they're likely to need. The urine results read like an infection: nitrite detected, leukocyte esterase “one plus”. Who records a lab result? The instrument or technologist produces the value, the lab verifies it, and the report's performer names the lab. Here the performer is a home care agency: Synthea's provider assignment isn't always realistic.

Who recorded what

For each resource in the visit, which “who” fields are filled in? FHIR has several, each with a precise meaning: performer did it, requester asked for it, author wrote it, recorder typed it, asserter vouched for it.

$ jq -r --arg enc $enc --arg ref "urn:uuid:$enc" '
  .entry[].resource
  | select(.id == $enc or (tostring | contains($ref)))
  | select(.resourceType != "Provenance")
  | ["participant", "performer", "requester", "author",
     "recorder", "asserter", "provider"] as $who
  | "\(.resourceType): \([$who[] as $k | select(has($k))
     | $k] | join(" "))"' lindsay.json | sort | uniq -c
      2 Claim: provider
      2 DiagnosticReport: performer
      1 DocumentReference: author
      1 Encounter: participant
      2 ExplanationOfBenefit: provider
      1 MedicationRequest: requester
     21 Observation: 
     10 Procedure: 
$ jq -r --arg ref "urn:uuid:$enc" '.entry[].resource
  | select(.resourceType == "MedicationRequest")
  | select(.encounter.reference == $ref)
  | .authoredOn, .requester.display,
    .medicationCodeableConcept.text' lindsay.json
2023-03-19T14:09:32-04:00
Dr. Angele108 Bogan287
nitrofurantoin, macrocrystals 25 MG / nitrofurantoin, monohydrate 75 MG Oral Capsule

The 21 Observations and 10 Procedures, including the triage and vital signs a nurse would have done, name nobody. A production system would carry Observation.performer on vitals, so you could ask “which nurse took these?” In Synthea, the one physician on the encounter is the only person in the room.

MedicationRequest.requester is the clearest case: the specification defines it as who initiated the request and is responsible for its activation. It's the prescriber, not the pharmacist who fills it and not the nurse who hands over the first dose. Pharmacy's work would show up as a MedicationDispense, and the nurse's as a MedicationAdministration, each with its own time.

Follow references, then check them

The prescription says why it was written, through reasonReference. Follow it, and look at every cystitis Condition in the record next to the encounter each one claims to come from:

$ jq -r --arg ref "urn:uuid:$enc" '.entry[].resource
  | select(.resourceType == "MedicationRequest")
  | select(.encounter.reference == $ref)
  | .reasonReference[0].reference' lindsay.json
urn:uuid:46976cf7-b0bf-be20-7c94-958542c8b48e
$ jq -r '[.entry[].resource] as $r
  | ($r | map(select(.resourceType == "Encounter")
      | {key: ("urn:uuid:" + .id),
         value: (.period.start[0:10] + " " + .class.code)})
      | from_entries) as $when
  | $r[] | select(.resourceType == "Condition")
  | select(.code.text | test("cystitis"))
  | [.id[24:], .onsetDateTime[0:10],
     .abatementDateTime[0:10], $when[.encounter.reference]]
  | @tsv' lindsay.json
958542c8b48e	2022-10-14	2022-10-14	2021-11-12 AMB
9686c12c3106	2023-03-13	2023-03-20	2022-11-18 AMB
$ jq -r '.entry[].resource | select(.resourceType == "Encounter")
  | select(.period.start | startswith("2023-03"))
  | [.period.start[0:16], .class.code, .type[0].text]
  | @tsv' lindsay.json
2023-03-13T20:33	VR	Videotelephony encounter (procedure)
2023-03-15T18:15	AMB	Encounter for problem (procedure)
2023-03-17T16:35	VR	Indirect encounter (procedure)
2023-03-19T11:55	EMER	Encounter for symptom (procedure)

The prescription points at …958542c8b48e, a cystitis that began and ended on 14 Oct 2022, five months before this visit. The current episode, …9686c12c3106, began on 13 Mar 2023 and resolved on the 20th, but its Condition.encounter points to a well-child visit from November 2022, four months before the infection started. Both links are valid references to resources that exist; neither is right.

Synthetic data has wiring bugs too. A reference that resolves is not a reference that makes sense: compare the times at both ends before you trust it. Real records have the same problem when a note is attached to the wrong visit or a problem is entered at a later appointment.

Conditions are also a reminder that a diagnosis doesn't belong to one visit. The third command shows that the episode ran across four encounters in a week: a video visit, a clinic visit, an indirect follow-up, then the emergency visit. Condition.onsetDateTime says when the problem began, recordedDate when someone wrote it down, abatementDateTime when it ended. None of them is the encounter's start.

Notes, discharge, coding and billing

The clinical note is a DocumentReference with base64 text in content[0].attachment.data. Decode it and pick out three lines:

$ jq -r --arg ref "urn:uuid:$enc" '.entry[].resource
  | select(.resourceType == "DocumentReference")
  | select(.context.encounter[0].reference == $ref)
  | .date, (.content[0].attachment.data | @base64d)' \
  lindsay.json | grep -o -e '^20[-0-9T:.]*' \
    -e 'is a [0-9]* year-old' -e '^- .*discharge.*'
2023-03-19T11:55:36.082-04:00
2023-03-19
is a 15 year-old
- patient discharge (procedure)

The note is dated 11:55, when Lindsay arrived, yet it lists her discharge, which the timeline puts at 14:09. It also gives her age at the visit, 15. Real notes carry the time they were written or signed, often hours later. Either way, a note's date is about the document, not the events in it.

Discharge appears twice: a “Patient discharge” Procedure at 14:09 and Encounter.period.end at 14:19. For inpatient stays, FHIR also records where the patient went in Encounter.hospitalization.dischargeDisposition.

Then the back office takes over. Coders turn the record into standard codes, and billing turns codes into a Claim. For this visit Synthea produced one claim for the institution's services and another for the prescription, and paired each with an ExplanationOfBenefit (what the insurer decided):

$ jq --arg ref "urn:uuid:$enc" '.entry[].resource
  | select(.resourceType == "Claim")
  | select(.item[0].encounter[0].reference == $ref)
  | {type: .type.coding[0].code, created,
     payer: .insurance[0].coverage.display,
     diagnosis, items: (.item | length),
     codes: [.item[].productOrService.coding[0].system]
       | unique,
     total: "\(.total.value) \(.total.currency)"}' \
  lindsay.json
{
  "type": "pharmacy",
  "created": "2023-03-19T14:19:32-04:00",
  "payer": "Humana",
  "diagnosis": null,
  "items": 1,
  "codes": [
    "http://www.nlm.nih.gov/research/umls/rxnorm"
  ],
  "total": "129.94 USD"
}
{
  "type": "institutional",
  "created": "2023-03-19T14:19:32-04:00",
  "payer": "Humana",
  "diagnosis": null,
  "items": 12,
  "codes": [
    "http://loinc.org",
    "http://snomed.info/sct"
  ],
  "total": "4476.29 USD"
}
$ jq -r --arg ref "urn:uuid:$enc" '.entry[].resource
  | select(.resourceType == "ExplanationOfBenefit")
  | select(.item[0].encounter[0].reference == $ref)
  | "\(.type.coding[0].code): \(.total[0].amount.value)"
    + " billed, \(.payment.amount.value) paid"' lindsay.json
pharmacy: 129.94 billed, 0.0 paid
institutional: 4476.29 billed, 3581.0319999999997 paid

Three things to notice. Both claims are created at 14:19, when the visit ended: billing happens after the care, and a claim's dates are the worst possible source for the time of a clinical event. The claims carry no diagnosis, and the institutional claim's items are coded in SNOMED CT and LOINC, the languages of the chart. Real US claims carry ICD-10-CM diagnosis codes and procedure codes from billing code sets, and in Canada, hospitals report to CIHI with ICD-10-CA and CCI. That translation, done by a coder reading the chart, is the “coding” step, and Synthea skips it. Finally, the insurer paid 3581.0319999999997 dollars: money held as binary floating point. Never do that in your own code; store cents as integers or use a decimal type.

Identifiers

Last stop: who is this patient, according to the record?

$ jq -r '.entry[0].resource | .identifier[]
  | [.type.coding[0].code // "-", .system, .value]
  | @tsv' lindsay.json
-	https://github.com/synthetichealth/synthea	46976cf7-b0bf-be20-39a5-9f425a52886d
MR	http://hospital.smarthealthit.org	46976cf7-b0bf-be20-39a5-9f425a52886d
SS	http://hl7.org/fhir/sid/us-ssn	999-37-5783
DL	urn:oid:2.16.840.1.113883.4.3.25	S99973582
$ jq -r '.entry[0].resource.address[0]
  | [.city, .state, .postalCode, .country] | @tsv' lindsay.json
Worcester	MA	01607	US

Four identifiers, each with a system that says who issued it. The first is Synthea's own id. The MR one is a medical record number issued by a (fictional) hospital. The SS and DL ones are a US Social Security number and a driver's licence number, both generated by Synthea.

Real patients collect identifiers: an MRN from every hospital and clinic they've visited, an enterprise ID if those organizations share a master patient index, an insurance member ID or a provincial health card number. An MRN is unique only within the system that issued it, which is why a FHIR Patient identifier pairs a system with the value. When a clerk can't find a patient because of a typo and registers them again, one person becomes two records, each holding part of the story. So never assume one MRN per person across hospitals. Week 3 deals with finding and merging duplicates.

Canada: the same workflow; the shared identifier is usually the provincial health card number. Each province issues its own (Ontario's is the OHIP health card), alongside each facility's MRN.

A Canadian run

The synthea-international project publishes configuration for other countries: demographics, postal codes, hospitals and payers. The Canadian one is a directory of resource files that override the jar's own when they come first on the Java classpath. That's why this command uses -cp … App instead of -jar:

$ ls ca/src/main/resources
geography
payers
providers
synthea.properties
$ java -cp ca/src/main/resources:synthea-with-dependencies.jar \
    App -p 5 -s 42 -cs 42 -r 20261031 \
    --exporter.baseDirectory=./ontario/ Ontario 2>&1 \
  | grep -e ' -- ' -e Records
2 -- Wilfredo622 Fritsch593 (15 y/o M) Haldimand County, Ontario  (20330)
3 -- Ezekiel373 Walter473 (27 y/o M) Windsor, Ontario  (36663)
4 -- Shalanda398 Kelsie51 Kris249 (30 y/o F) Toronto, Ontario  (41576)
5 -- Jona712 Bonnie873 Gutmann970 (67 y/o F) Hamilton, Ontario  (93802)
1 -- Corie618 Sofia418 Auer97 (91 y/o F) Richmond Hill, Ontario DECEASED (126447)
1 -- Mellie476 Cuc113 Wintheiser220 (86 y/o F) Richmond Hill, Ontario DECEASED (119777)
1 -- Yesenia104 Rosella686 Koss676 (88 y/o F) Richmond Hill, Ontario DECEASED (121255)
1 -- Glenda787 Lynetta635 Schowalter414 (81 y/o F) Richmond Hill, Ontario DECEASED (123702)
1 -- Linnea167 Pfeffer420 (82 y/o F) Richmond Hill, Ontario DECEASED (113977)
1 -- Rhona164 Cremin516 (91 y/o F) Richmond Hill, Ontario DECEASED (130426)
1 -- Kanesha23 Avril120 Sanford861 (101 y/o F) Richmond Hill, Ontario  (144253)
Records: total=11, alive=5, dead=6

Ontario cities this time, and some familiar first names. This run also produced six deceased patients on the way to five living ones; we didn't dig into why. What did the configuration change?

$ on=$(ls ontario/fhir/Shalanda398_*.json)
$ jq -r '.entry[0].resource | .identifier[]
  | [.type.coding[0].code // "-", .system, .value]
  | @tsv' $on
-	https://github.com/synthetichealth/synthea	46ee9d82-b52c-856d-069b-5064ff052225
MR	http://hospital.smarthealthit.org	46ee9d82-b52c-856d-069b-5064ff052225
SS	http://hl7.org/fhir/sid/us-ssn	999-44-2741
DL	urn:oid:2.16.840.1.113883.4.3.25	S99962205
PPN	http://hl7.org/fhir/sid/passport-USA	X44936501X
$ jq -r '.entry[0].resource.address[0]
  | [.city, .state, .postalCode, .country] | @tsv' $on
Toronto	Ontario	M5T	CA
$ jq -r '.entry[].resource | (.code // .vaccineCode
  // .medicationCodeableConcept).coding[0].system
  | select(.)' $on | sort | uniq -c | sort -rn
    112 http://snomed.info/sct
     69 http://loinc.org
     15 http://www.nlm.nih.gov/research/umls/rxnorm
      8 http://hl7.org/fhir/sid/cvx
$ jq -r '.entry[].resource | select(.resourceType == "Claim")
  | "\(.insurance[0].coverage.display) \(.total.currency)"' \
  $on | sort | uniq -c
     58 Ontario Health Insurance USD

The address is Canadian, with only the first three characters of the postal code, and the payer is Ontario Health Insurance. Everything else is still American. The configuration localizes where people live and who pays, not how they're identified or coded.

Tested: the Ontario run gave Ontario addresses and an Ontario payer, but SSN, US driver's licence and US passport identifiers, no health card number, RxNorm and CVX codes, and claims in USD. For Canadian work, add a health card identifier yourself, with a system you control, before you build anything on it.

Writing it down like a nurse

Now turn the jq output into something a person can read. Here is a model for your build: first the account, in the words a triage nurse might use at handover, then the timeline that proves it. Everything in both comes from the runs above.

A 15-year-old girl came in to the emergency department just before noon with cystitis. It had started six days earlier, and she'd had a video visit, a clinic visit and a follow-up about it since. We took her history, triaged her at 12:10 and did vitals at 12:25; her triage score said she'd need one resource (one test or treatment). The doctor examined her at 12:30. We started a urinalysis at 13:29 and collected the sample at 13:39. Results were back at 13:59: nitrites positive, leukocytes one plus. The doctor started antibiotics, and she was discharged at 14:09 with a prescription for nitrofurantoin. She was out of the department by 14:19.

She was 15 at this visit in 2023; the “19” in Synthea's patient list is her age on our 2026 reference date.

And the timeline. Each row is one line of the jq output, translated:

TimeWhat happenedFHIR resource.field
11:55Arrives; registered in the emergency departmentEncounter.period.start (class EMER)
11:55History takenProcedure.performedPeriod.start
11:55H&P note (stamped at arrival)DocumentReference.date
12:04Symptoms discussedProcedure.performedPeriod.start
12:10TriagedProcedure.performedPeriod.start
12:25Vital signs takenProcedure.performedPeriod.start
12:30Triage score and 5 vital signs chartedObservation.effectiveDateTime
12:30Doctor's history and physicalProcedure.performedPeriod.start
13:29Urinalysis startedProcedure.performedPeriod.start
13:39Urine sample collectedProcedure.performedPeriod.start
13:59Urinalysis results (15 values, 1 report)Observation.effectiveDateTime, DiagnosticReport.effectiveDateTime
13:59Antibiotic therapy startedProcedure.performedPeriod.start
14:09Discharged; nitrofurantoin prescribedProcedure.performedPeriod.start, MedicationRequest.authoredOn
14:19Leaves; visit closed and billedEncounter.period.end, Claim.created

Two rows deserve a second look: a note stamped earlier than most of what it describes, and results and treatment in the same minute at 13:59. Plausible, but check it rather than assume it.

Your build this week

  1. Generate 10 Synthea patients; pick an emergency or inpatient encounter. Use a different seed or patient from ours.
  2. List its resources: Encounter, Conditions, Observations, Procedures, MedicationRequests, Claim.
  3. Write a half-page account as a nurse would tell it.
  4. Turn it into a timeline linking each event to a FHIR resource and field.
  5. Start the glossary; aim for 100 terms by week 6. The course glossary is a starting point; write your own definitions.

Go further: interview a nurse or registration clerk about one shift. Ask what they record, when they record it, and what they do when the system is slow. You'll hear about charting after the fact and workarounds no data model mentions.

AI this week: have it explain clinical terms; check each against MedlinePlus or a similar reference.

Exercises

  1. Who records a lab result, and which FHIR resources hold it? Answer for a real hospital, then check what Synthea fills in for one of your patients' DiagnosticReports and their result Observations.
  2. Why do duplicate patient records appear? Name three causes at the registration desk, and say which identifier would have prevented each.
  3. Why isn't an encounter's start time the time of everything in it? Find an inpatient encounter in your population and compute the largest gap between Encounter.period.start and the time of a resource that references it.
  4. Modify timeline.jq so it also prints the end of each performedPeriod. Which Procedure in Lindsay's visit is longest?
  5. Write a jq filter that finds every reference in a bundle whose target doesn't exist in the bundle. Then write one that flags a Condition whose encounter ended before the condition's onset. How many does your population have?
  6. Using the ADT table, write the sequence of v2 events a hospital would send for a patient who arrives in the emergency department, is admitted to a medical ward, moves to intensive care, and goes home. For each event, which FHIR fields change?
  7. Find the ExplanationOfBenefit for one of your encounters and compute what the patient owed. Which fields did you use, and where did floating point get in your way?
  8. Canada track: generate five Ontario patients, add a health card identifier to each Patient with a system under https://example.org/, and decide what your code should do when a patient has no health card number.
  9. Stretch: load your 10 patients into the course HAPI server (lab setup) and rebuild the timeline with FHIR searches (Observation?encounter=… and friends) instead of jq. What does the server make easier, and what harder?

Read

Tested with

Every command on this page was run on 31 Oct 2026 with Synthea (master build of 21 Oct 2026) on OpenJDK 25.0.4.1, jq 1.7 and the Canada configuration from synthea-international. The outputs are copied from those runs. If you use the same seeds and reference date you should get the same patients; other Synthea builds will give different ones.


Course content © 2026 HeyItWorked. All rights reserved.

Site design adapted from The Missing Semester of Your CS Education under CC BY-NC-SA 4.0. See copyright and license.