HL7 v2 + patient identity

Week 3 · ~10 h

Most of what happens to a patient in a hospital is announced in a message. Registration admits someone, and every downstream system hears about it. A lab analyzer finishes a test, and the result travels to the chart. A nurse moves a patient to another bed, and pharmacy, the kitchen and billing all update their records. For more than three decades, most of those announcements have been written in HL7 Version 2, which HL7 International itself calls “the workhorse of electronic data exchange in the clinical domain”. FHIR gets the attention (that's week 4), but if you join an integration team, there is a good chance your first ticket is about a v2 interface.

This lecture covers how v2 messages are built, how they travel, what an acknowledgment does and doesn't promise, and the hardest part of the whole business: knowing which patient a message is about. Along the way we build a small bridge that receives ADT (admit, discharge, transfer) messages and keeps exactly one FHIR Patient per medical record number, however many times the sender repeats itself. Identity mistakes here duplicate patients or merge the wrong ones; delivery mistakes lose results. Both reach the bedside.

Done when

This week you build a bridge: a listener that receives HL7 v2 messages and keeps one FHIR Patient per medical record number. You are done when:

Anatomy of a message

Here is a complete admission message, the kind a registration system sends when a patient is admitted. It looks like four lines; the carriage-return section below shows why it isn't quite:

$ tr '\r' '\n' < adt.hl7
MSH|^~\&|REGADT|GENHOSP|BRIDGE|LAB|20261031093000||ADT^A01^ADT_A01|MSG00001|T|2.5.1
EVN|A01|20261031093000
PID|1||100234^^^GENHOSP^MR||DOE^JANE||19800214|F|||12 MAIN ST^^SPRINGFIELD^IL^62701
PV1|1|I|4W^401^A

Each line is a segment, and its first three characters say what kind: MSH is the message header, EVN the event, PID patient identification and PV1 the patient visit. Within a segment, | separates fields, numbered from 1, and people refer to them as segment-number: PID-3 is the patient identifier list, PID-5 the name, PID-7 the birth date, PID-8 administrative sex and PID-11 the address. In PV1, field 2 is the patient class (I for inpatient) and field 3 the assigned location: unit 4W, room 401, bed A.

Fields have structure of their own. ^ separates components: the name DOE^JANE is family name, then given name, and the identifier 100234^^^GENHOSP^MR is an ID number (component 1), an assigning authority (component 4, GENHOSP) and an identifier type (component 5, MR for medical record number). ~ separates repetitions of a field, because a patient can have several identifiers or several addresses. & separates subcomponents, and \ starts an escape sequence such as \T\ for a literal & or \F\ for a literal |.

Those five characters aren't fixed by the standard: each message declares its own. MSH-1 is the field separator, the | straight after MSH, and MSH-2 is ^~\&: the component, repetition, escape and subcomponent characters, in that order. Nearly everyone uses the defaults, but a parser that hard-codes them is betting that everyone always will.

The rest of MSH tells the receiver what it is looking at:

FieldMeaningIn our sample
MSH-3, MSH-4Sending application and facilityREGADT, GENHOSP
MSH-5, MSH-6Receiving application and facilityBRIDGE, LAB
MSH-7When the message was created20261031093000
MSH-9Message typeADT^A01^ADT_A01
MSH-10Control ID the sender uses to match up the replyMSG00001
MSH-11Processing ID: P production, T training, D debuggingT
MSH-12Version of the standard2.5.1

Many interfaces still run 2.3 or 2.3.1; the structure is the same, but fields were added and renamed between versions, so the interface spec names the version you build against.

The carriage-return trap

Above, we piped the file through tr to make it readable. Segments in HL7 v2 end with a carriage return (\r, byte 0x0D), not the newline (\n) that Unix tools expect. Look at the raw file:

$ wc -l adt.hl7
0 adt.hl7
$ od -c adt.hl7 | head -6
0000000   M   S   H   |   ^   ~   \   &   |   R   E   G   A   D   T   |
0000020   G   E   N   H   O   S   P   |   B   R   I   D   G   E   |   L
0000040   A   B   |   2   0   2   6   1   0   3   1   0   9   3   0   0
0000060   0   |   |   A   D   T   ^   A   0   1   ^   A   D   T   _   A
0000100   0   1   |   M   S   G   0   0   0   0   1   |   T   |   2   .
0000120   5   .   1  \r   E   V   N   |   A   0   1   |   2   0   2   6

wc -l counts newlines and finds none, and od -c shows the \r where the MSH segment ends. Line-oriented tools see one long line, terminals and editors may quietly draw \r as a line break and hide the difference, and Python's open() is the sneakiest of all: in text mode it translates \r into \n before your code sees the data. We'll trip over that in a moment.

Once you know about the trap, shell tools are fine for a quick look. Convert the separators, then let awk split on |:

$ tr '\r' '\n' < adt.hl7 | awk -F'|' '$1=="MSH" {print $9}'
ADT^A01^ADT_A01
$ tr '\r' '\n' < adt.hl7 | awk -F'|' '$1=="PID" {split($6, n, "^"); print n[1] ", " n[2]}'
DOE, JANE

Look at the numbering. Because MSH-1 is the |, awk's $9 is MSH-9, but in every other segment field n is $(n+1), so PID-5 is $6. That off-by-one is the classic bug in hand-written parsers.

Use a parser

awk is fine for a peek, but splitting on separators by hand eventually gets repetitions, escapes or missing trailing fields wrong. Real code should use a library: HAPI HL7v2 in Java, python-hl7 in Python, or your integration engine's parser. Here is python-hl7 in the REPL:

>>> import hl7
>>> msg = hl7.parse(open("adt.hl7").read())
>>> len(msg)
1
>>> msg = hl7.parse(open("adt.hl7", newline="").read())
>>> len(msg)
4
>>> msg["MSH.F10"], msg["PID.F3.R1.C1"], msg["PID.F7"]
('MSG00001', '100234', '19800214')
>>> str(msg.segment("PID")[5])
'DOE^JANE'
>>> msg["PID.F5.R1.C2"]
'JANE'
>>> on = hl7.parse(open("adt-on.hl7", newline="").read())
>>> str(on.segment("PID")[3])
'100236^^^GENHOSP^MR~9876543225^^^ON^JHN'
>>> on["PID.F3.R2.C1"], on["PID.F3.R2.C5"]
('9876543225', 'JHN')
>>> amp = hl7.parse(open("adt-amp.hl7", newline="").read())
>>> str(amp.segment("PID")[5])
'DOE\\T\\SMITH^JANE'
>>> amp["PID.F5.R1.C1"]
'DOE&SMITH'

The first attempt walks straight into the trap: open() turned every \r into \n, so python-hl7 found one segment instead of four. Passing newline="" keeps the bytes as they are. A key like "PID.F3.R1.C1" reads field 3, repetition 1, component 1. The Ontario sample has two repetitions in PID-3: the hospital MRN and a provincial health card number, typed JHN. And the last sample shows why you never compare raw field strings: the sender escaped an ampersand as \T\, and the accessor returns the unescaped value.

Language models are good at explaining a segment field by field. Check what they tell you against the spec page for your version: fields were added and renamed between versions, and a confident answer can describe the wrong one.

Message types and trigger events

MSH-9 in our sample is ADT^A01^ADT_A01: message code ADT, trigger event A01, and message structure ADT_A01. The trigger event is the real-world thing that happened, and a handful of them cover most of what you will see:

Several events share a structure: an A08 is sent with structure ADT_A01, because it carries the same segments. Week 1's encounter story is useful here. Each event is something a person did at a desk or a bedside, and the messages arrive in roughly the order the work happened. Roughly: retries and racing feeds mean an A08 can arrive before the A01 it updates, and a receiver must cope (case 6 in the broken set below). Process messages one at a time and in order on each connection; most feeds depend on it.

Getting messages across: MLLP

v2 messages usually travel over a plain TCP connection. TCP is a byte stream with no idea where one message ends and the next begins, so v2 adds a minimal framing layer, the Minimal Lower Layer Protocol (MLLP): a start byte 0x0B, the message, then the two bytes 0x1C 0x0D. That really is the whole protocol. Port 2575 is the conventional port.

We can watch it on the wire by putting socat between a sender and the listener we build later in this lecture, and asking it to dump every byte in hex. The awk keeps the first four bytes and the last three of each frame:

$ socat -x TCP-LISTEN:2576,reuseaddr TCP:localhost:2575 2> wire.log &
$ mllp_send --loose -f adt.hl7 -p 2576 localhost > /dev/null
$ awk '/^[<>]/ {print $1, $4; next} {print $1, $2, $3, $4, "...", $(NF-2), $(NF-1), $NF}' wire.log
> length=210
0b 4d 53 48 ... 41 1c 0d
< length=111
0b 4d 53 48 ... 0d 1c 0d

Both frames start with 0b followed by 4d 53 48 (“MSH”) and end with 1c 0d. The second frame, flowing back, is the acknowledgment.

Tested: mllp_send --loose dropped the file's final \r before framing it (the frame ends 41 1c 0d: “A”, then the trailer), while the ACK kept it (0d 1c 0d). Receivers should accept both. Without --loose, mllp_send expects a file that is already framed and fails with MLLPException: buffer not terminated, exit status 1.

MLLP has no encryption and no authentication. Interfaces run it inside a VPN or a TLS tunnel between known hosts, and that network path belongs in the interface spec just as much as the message format does.

Acknowledgments: what AA actually promises

Every message gets a reply. In the basic (“original”) acknowledgment mode, the receiver sends back an ACK message whose MSA segment carries a code and echoes the control ID from the sender's MSH-10:

The ERR segment points at the problem with a location such as PID^1^7 (segment, sequence, field) and a code from HL7 table 0357, such as 101 required field missing, 102 data type error or 205 duplicate key identifier. Here is our listener answering three messages from the broken set:

$ for f in adt-baddob.hl7 adt-nomrn.hl7 adt-prod.hl7; do mllp_send --loose -f $f -p 2575 localhost | tr '\r' '\n' | grep -E '^(MSA|ERR)'; done
MSA|AE|MSG00002
ERR||PID^1^7|102^Data type error^HL70357|E
MSA|AE|MSG00003
ERR||PID^1^3|101^Required field missing^HL70357|E
MSA|AR|MSG00004
ERR||MSH^1^11|202^Unsupported processing id^HL70357|E

Now the important part. A sender treats AA as “you have it; I can forget it”. If the receiver says AA and then fails to store the message, the message is gone and nobody knows. So the rule for this course is: send AA only after the write has committed. Not when the bytes arrive, not when the message parses, but when the patient is safely in the FHIR server.

Tested: OIE's auto-ACK answered AA to an invalid birth date and while its outbound link was down (2 received, 2 errors): AA meant “received”, not “valid” or “delivered”. HAPI's HL7v2 parser rejected the date.

Integration engines can usually acknowledge as soon as a message arrives, which keeps the sender fast. That is a legitimate design if the engine then stores the message durably and retries delivery itself, but it moves the guarantee: AA now means “the engine has it”, and the engine's queue becomes the thing someone must watch. Know which kind of AA your interface sends, and write it down.

Version 2 also defines an “enhanced” mode with two layers: a commit acknowledgment (CA, CE or CR) once the message is safely stored, and an application acknowledgment later. Many interfaces use original mode; the interface spec says which.

Delivery: at least once, so make writes idempotent

What should a sender do when no ACK comes back? It can't tell whether the message was lost on the way, or processed with the ACK lost on the way back. The safe choice is to send it again, so senders keep resending until they get an ACK. Delivery is therefore at least once, and you will see duplicates: resends after a timeout, a restarted sender replaying its queue, an engine failing over to its standby.

Your receiver turns at-least-once delivery into exactly-once effects by making the write idempotent: processing the same message twice must leave the same state as processing it once. For patients, that means keying the write on the identifier instead of creating a new record each time. FHIR has exactly the tool for this, a conditional update. Compare it with a plain create:

$ export FHIR=http://localhost:8080/fhir MRN=https://genhosp.example.org/mrn
$ cat patient.json
{"resourceType": "Patient", "identifier": [{"system": "https://genhosp.example.org/mrn", "value": "100900"}], "name": [{"family": "ROE", "given": ["RICHARD"]}]}
$ for i in 1 2; do curl -s -o /dev/null -w '%{http_code}\n' -X POST "$FHIR/Patient" -H 'Content-Type: application/fhir+json' -d @patient.json; done
201
201
$ curl -s "$FHIR/Patient?identifier=$MRN|100900&_summary=count" | jq .total
2
$ curl -s -o /dev/null -w '%{http_code}\n' -X PUT "$FHIR/Patient?identifier=$MRN|100900" -H 'Content-Type: application/fhir+json' -d @patient.json
412

Two POSTs, two patients with the same MRN. That is the duplicate-patient bug, and it is a safety problem, not a tidiness one: each copy holds part of the record, and a clinician reading one can miss an allergy recorded on the other. A conditional PUT says “update the patient with this identifier, or create one if there is none”. Once duplicates exist, it refuses to guess and answers 412 Precondition Failed. A person has to sort that out.

Why not deduplicate on MSH-10 instead? Control IDs are only unique per sender, a sender can reuse them after a restart, and the same facts can arrive again in a new message with a new control ID (case 5 below). Use MSH-10 to match ACKs and to trace a message through your logs; use the patient's identifier to decide what to write.

Patient identity

The identifier in PID-3 is a medical record number: unique within one facility's registration system and meaningless anywhere else. MRN 100234 at General Hospital and 100234 at the clinic down the road are different people. That is why the identifier carries an assigning authority (GENHOSP), and why a FHIR identifier is always a system plus a value. Our bridge maps each assigning authority it knows to a system URI and rejects messages from one it doesn't.

One person usually has many MRNs: one per facility, plus whatever the lab, the pharmacy and the clinic assigned. Health systems tie them together with an enterprise master patient index (EMPI), which links records it believes belong to the same person under an enterprise ID. Between organizations, IHE's PIX profile (Patient Identifier Cross-referencing) does the same job, and PDQ (Patient Demographics Query) lets a system find a patient by demographics.

Never match patients on name and birth date alone. Twins share a birth date, common names collide, and typos and name changes split one person into two. Matching is the EMPI's job, with people reviewing the uncertain cases. An interface trusts the identifiers it is given and fails loudly when they are missing, which is what the AE for case 3 does.

When registration discovers that two records are the same person, it merges them and sends ADT^A40: PID carries the surviving identifier and an MRG segment carries the one being retired. Don't delete the retired record, because other systems may still point at it, and merges are sometimes reversed. In FHIR, set it to active: false and link it to the survivor with a link of type replaced-by.

Canada: the same workflow; the identifier shared across organizations is usually the provincial health card number, alongside each facility's MRN. In v2 it typically arrives as another repetition of PID-3, typed JHN, like the Ontario sample above. Health card rules differ by province, so the interface spec says which identifier to key on.

Building the bridge

Now we have the pieces. The bridge listens for MLLP, parses each message, checks the fields it needs, maps PID to a FHIR Patient, upserts it with a conditional PUT, and only then sends AA. A bad message gets AE or AR with an ERR segment, and nothing is written. If the FHIR server can't be reached, the bridge sends no ACK at all and closes the connection, so the sender keeps the message and tries again. The heart of it is the part that decides what to answer:

def process(msg):
    ctl = field(msg, "MSH.F10")
    try:
        status, location = upsert(to_patient(msg))
    except Reject as e:
        log.warning("%s %s: %s at %s, nothing written",
                    ctl, e.code, e.why, e.where)
        ack = msg.create_ack(e.code)
        return hl7.parse(f"{ack}ERR||{e.where}|{e.why}|E\r")
    except OSError as e:  # FHIR down: no ACK, so it retries
        log.error("%s write failed (%s), no ACK sent",
                  ctl, e)
        return None
    log.info("%s AA after HTTP %s %s", ctl, status, location)
    return msg.create_ack("AA")


async def handle(reader, writer):
    try:
        while not writer.is_closing():
            # one message at a time keeps the feed in order
            ack = process(await reader.readmessage())
            if ack is None:
                break
            writer.writemessage(ack)
            await writer.drain()
    except asyncio.IncompleteReadError:
        pass  # the sender hung up
    finally:
        writer.close()

The mapping and validation live in to_patient, and the write in upsert, which turns a 412 into AE 205.

Download bridge.py (138 lines) and the sample messages used on this page: patient.json, adt.hl7, adt-on.hl7, adt-amp.hl7, adt-baddob.hl7, adt-nomrn.hl7, adt-prod.hl7, adt-dupe.hl7, adt-newctl.hl7, adt-a08-first.hl7, adt-a01-late.hl7, adt-zseg.hl7.

Start it in one terminal:

$ python3 bridge.py
listening for MLLP on port 2575

and send the admission from another:

$ mllp_send --loose -f adt.hl7 -p 2575 localhost | tr '\r' '\n'
MSH|^~\&|BRIDGE|LAB|REGADT|GENHOSP|20261031213954||ACK^A01^ACK|6304213954392730KOHI|T|2.5.1
MSA|AA|MSG00001

$ curl -s "$FHIR/Patient?identifier=$MRN|100234" | jq '.total, .entry[0].resource.name, .entry[0].resource.meta.versionId'
1
[
  {
    "family": "DOE",
    "given": [
      "JANE"
    ]
  }
]
"1"

The ACK echoes our control ID in MSA-2, and the FHIR server has one Jane Doe. The bridge's terminal shows that the write (HTTP 201, created) happened before the AA:

MSG00001 AA after HTTP 201 http://localhost:8080/fhir/Patient/1002/_history/1

Now behave like a sender that never saw the ACK, and send it three more times:

$ for i in 1 2 3; do mllp_send --loose -f adt.hl7 -p 2575 localhost | tr '\r' '\n' | grep MSA; done
MSA|AA|MSG00001
MSA|AA|MSG00001
MSA|AA|MSG00001
$ curl -s "$FHIR/Patient?identifier=$MRN|100234" | jq '.total, .entry[0].resource.meta.versionId'
1
"1"

In the bridge's terminal:

MSG00001 AA after HTTP 200 http://localhost:8080/fhir/Patient/1002/_history/1
MSG00001 AA after HTTP 200 http://localhost:8080/fhir/Patient/1002/_history/1
MSG00001 AA after HTTP 200 http://localhost:8080/fhir/Patient/1002/_history/1

Still one patient. The conditional PUT found the existing record and answered 200 instead of 201, and HAPI noticed that nothing had changed and didn't even create a new version. Remember the duplicate MRN our two POSTs left behind? A message for that patient now gets an AE instead of a guess:

$ mllp_send --loose -f adt-dupe.hl7 -p 2575 localhost | tr '\r' '\n' | grep -E '^(MSA|ERR)'
MSA|AE|MSG00007
ERR||PID^1^3|205^Duplicate key identifier^HL70357|E

The escaped ampersand is stored unescaped:

$ mllp_send --loose -f adt-amp.hl7 -p 2575 localhost | tr '\r' '\n' | grep MSA
MSA|AA|MSG00005
$ curl -s "$FHIR/Patient?identifier=$MRN|100235" | jq '.entry[0].resource.name[0].family'
"DOE&SMITH"

Look at what the bridge logs: control IDs, ACK codes and server URLs. Never names, birth dates or MRNs. Logs get copied into tickets and chat, and week 5 adds the test that proves no identifier ever reaches them (case 10).

When the FHIR server is down

The interesting failure is the one in the middle: the message is fine, but we can't store it. Freeze the FHIR server, send, then thaw it and send again:

$ docker pause hapi
hapi
$ mllp_send --loose -f adt.hl7 -p 2575 localhost | tr '\r' '\n'; echo "exit status: ${PIPESTATUS[0]}"

exit status: 0
$ docker unpause hapi
hapi
$ mllp_send --loose -f adt.hl7 -p 2575 localhost | tr '\r' '\n' | grep MSA
MSA|AA|MSG00001
$ curl -s "$FHIR/Patient?identifier=$MRN|100234" | jq '.total, .entry[0].resource.meta.versionId'
1
"1"

In the bridge's terminal:

MSG00001 write failed (timed out), no ACK sent
MSG00001 AA after HTTP 200 http://localhost:8080/fhir/Patient/1002/_history/1

With the server frozen, the bridge's HTTP call timed out after 10 seconds, it logged the failure, and it closed the connection without an ACK. Once the server was back, the resend went through, and there is still exactly one patient, still at version 1. Note what mllp_send did, though: with no ACK, it printed nothing and exited with status 0. A real sender must treat a missing ACK as a failure and retry. Check what yours does before you trust its exit code.

Tested: we froze the server with docker pause because stopping and restarting this HAPI image lost its data: the database lives inside the container. Your lab's FHIR server is disposable; production ones are not.

Integration engines

Few teams run hand-written listeners like ours in production. Hospitals run an integration engine, such as Open Integration Engine (the open-source fork of Mirth Connect), InterSystems HealthShare Health Connect or Rhapsody. The engine receives each feed once and routes it to every system that needs it, with transformers, filters, queues, retries, monitoring and alerting built in. In OIE our bridge would be one channel: an MLLP listener as the source, a JavaScript transformer for the PID mapping, and an HTTP sender as the destination.

An engine changes who writes the code, not what has to be true: nothing is acknowledged before it's safe, duplicates don't become duplicate patients, and broken messages land somewhere a person will look. Week 6 deploys an OIE channel. This week, build the bridge yourself, so that you know what the engine's settings mean.

The broken message set

Real feeds are messier than any sample. Keep these as files in your repo, each with its expected result, and run them in CI:

#Broken caseExpected result
1Segments separated by \n instead of \rOne rule (normalize or reject), applied and logged consistently
2PID-7 birth date NOT_A_DATEAE with an ERR segment pointing at PID-7
3PID-3 MRN missingAE: there is nothing to upsert on
4Exact resend (same MSH-10)AA again; still one patient
5Resend with a new MSH-10Still one patient (conditional PUT)
6A08 update arrives before its A01One patient, no error
7Name with an escaped ampersand (\T\)Stored as “&”, not “\T\”
8Unknown Z-segment (ZPI)Ignored; still AA
9MSH-11 = P sent to a TEST listenerAR, logged, nothing written
10Canary identifiers in PIDNever appear in any log

Each case encodes a decision, and case 1 is yours to make: normalize \n to \r or reject, but do the same thing every time and log it. You need your own sender for case 1, because mllp_send --loose rewrites line endings before framing. Our bridge gives cases 2, 3 and 9 the expected answers above, and 4 and 7 as well.

$ for f in adt-newctl.hl7 adt-a08-first.hl7 adt-a01-late.hl7 adt-zseg.hl7; do mllp_send --loose -f $f -p 2575 localhost | tr '\r' '\n' | grep MSA; done
MSA|AA|MSG00099
MSA|AA|MSG00100
MSA|AA|MSG00101
MSA|AA|MSG00102
$ for m in 100234 100240; do curl -s "$FHIR/Patient?identifier=$MRN|$m&_summary=count" | jq .total; done
1
1

That covers cases 5, 6 and 8: a resend with a new control ID, an A08 arriving before its A01, and an unknown ZPI segment. Each patient still exists exactly once.

AI this week: have it generate more broken cases; decide each expected result before you run it.

Exercises

  1. Why doesn't an AA prove the message was stored? Find the setting in an integration engine that decides when it sends AA, and say what AA means under each choice.
  2. What breaks if you split a raw HL7 file on \n? Show it twice: once with a shell tool, once with Python's open().
  3. Why is MSH-10 alone not enough to detect a resend? Give two situations from this lecture where it fails.
  4. Write a one-liner that counts segments by type in a raw HL7 file (hint: tr, cut, sort, uniq -c). Then count message types (MSH-9) in a file that holds many messages.
  5. Turn the broken message set into files plus an expected-results list, and write a script that sends each one and checks the ACK code. Make CI fail on any mismatch.
  6. Implement A40: keep the survivor active, set the other record to active=false and link it with replaced-by. Done when an A40 leaves exactly one active record. What should happen if the A40 names a record you never received?
  7. Kill test: send 200 messages with a sender that retries until it gets an ACK, and kill -9 the bridge in the middle of the feed. Restart it. Do you have exactly 200 patients? Explain why, or why not.
  8. Canada track: map the JHN repetition of PID-3 to a second FHIR identifier. Which identifier should the conditional PUT key on, and what happens when a patient's health card is replaced?
  9. Stretch: accept a VXU^V04 immunization message and write a FHIR Immunization. Public-health registries publish their own guides; in the US, start with CDC's immunization guide and NIST's test tools.

For more drill on this week's skills, work through the week 3 practice problems.

Read

Tested with

Every command on this page was run on 31 Oct 2026 against the course lab: a local HAPI FHIR 8.12.0 server in Docker and python-hl7 0.4.5. The outputs are copied from those runs. Yours will differ in timestamps, control IDs and server ids.


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.