← All writing

The 837 claim file, explained for developers

Loops, segments and delimiters: a developer's mental model for reading and generating X12 837 healthcare claims.

edix12healthcaredotnetcsharp

TL;DR: An 837 looks like line noise, but it is a tree serialized as flat text. Once you read the delimiters from the ISA header, peel off the three envelopes and follow the HL segments, you can read (and debug) any professional claim file. I’ll walk through one synthetic claim segment by segment and finish with a small C# tokenizer you can build on.

The problem

The first time I opened an 837 file, I was looking at something like this:

ISA*00*          *00*          *ZZ*SUBMITTERID    *ZZ*RECEIVERID     *261130*1200*^*00501*000000001*0*T*:~GS*HC*SUBMITTERID*RECEIVERID*20261130*1200*1*X*005010X222A1~ST*837*0001*005010X222A1~BHT*0019*00*BATCH0001*20261130*1200*CH~NM1*41*2*ACME BILLING SERVICE*****46*TGJ23~...

No line breaks, no field names, a lot of asterisks. The ticket said “claims for one payer are rejecting, please look”. The documentation was a 700-page implementation guide that assumes you already know what a “loop” is.

If you work on claims software in the US, sooner or later you end up here. The 837 is the HIPAA-mandated electronic format for submitting healthcare claims, and almost every clearinghouse, payer and billing system speaks it. The good news: the format is strict and very regular. Once you have the right mental model, it stops being scary and becomes boring, which is exactly what you want from a file format.

This is that mental model, the one I wish someone had handed me on day one.

The core idea

An 837 is a tree, written out as a flat list of segments. Three ideas get you most of the way:

  1. Delimiters tell you how to split the text into segments, elements and components.
  2. Envelopes wrap the claim data the way an HTTP request wraps a JSON body.
  3. Loops, chained together by HL (hierarchical level) segments, give the tree its shape.

Delimiters come from the file, not from your code

Every segment ends with a segment terminator, and every segment’s fields (called elements) are separated by an element separator. Some elements are composites made of smaller components, split by a component separator.

You’ll usually see ~, * and :. Usually. The actual characters are declared by the very first segment, ISA, which is fixed-width (106 characters including its terminator) precisely so a parser can find them before it knows anything else:

Delimiter Where it lives Typical value
Element separator character at index 3 (right after ISA) *
Repetition separator ISA11, index 82 ^
Component separator ISA16, index 104 :
Segment terminator the character right after ISA16, index 105 ~

Hard-coding * and ~ works right up until a trading partner sends | and newline. Read them from the ISA every time.

Three envelopes, like nesting dolls

ISA ─ Interchange (one file, one sender → one receiver)
 └─ GS ─ Functional group (a batch of one transaction type, e.g. HC = claims)
     └─ ST ─ Transaction set (one 837, which can hold many claims)
         ...claim data...
     └─ SE
 └─ GE
IEA

Each opening segment has a closing partner, and they share a control number: ISA13 must equal IEA02, GS06 must equal GE02, and ST02 must equal SE02. The closing segments also carry counts, which we’ll get to in the gotchas.

Loops form the hierarchy

Inside the ST/SE, data is grouped into loops: runs of segments that belong together, named by numbers from the implementation guide. For an 837P (professional), the shape is:

1000A  Submitter
1000B  Receiver
2000A  Billing provider            HL*1**20*1
 └─ 2010AA  Billing provider name/address/NPI
 └─ 2000B  Subscriber              HL*2*1*22*?
     └─ 2010BA  Subscriber name/ID
     └─ 2010BB  Payer
     └─ 2000C  Patient             HL*3*2*23*0   (only if patient ≠ subscriber)
     └─ 2300  Claim                CLM
         └─ 2400  Service line     LX + SV1

Loop IDs never appear in the file. You infer them from which segment you’re looking at and what came before it. The HL segments are the only explicit structure:

HL * 2 * 1 * 22 * 0
     │   │   │    └─ HL04: does this level have children? (1 = yes, 0 = no)
     │   │   └────── HL03: level code (20 = billing provider, 22 = subscriber, 23 = patient)
     │   └────────── HL02: parent HL ID
     └────────────── HL01: this HL's ID

That’s a parent pointer. It’s a tree serialized as a flat list, which is a structure every developer has built before.

Walking through one claim

Here’s a complete, minimal 837P with one claim and one service line. Everything in it is synthetic: the patient is JOHN DOE, member ID XYZ000000001, and the NPI 1234567893 is a checksum-valid test value. I’ve put each segment on its own line for readability. Real files often don’t.

ISA*00*          *00*          *ZZ*SUBMITTERID    *ZZ*RECEIVERID     *261130*1200*^*00501*000000001*0*T*:~
GS*HC*SUBMITTERID*RECEIVERID*20261130*1200*1*X*005010X222A1~
ST*837*0001*005010X222A1~
BHT*0019*00*BATCH0001*20261130*1200*CH~
NM1*41*2*ACME BILLING SERVICE*****46*TGJ23~
PER*IC*BILLING CONTACT*TE*5555550100~
NM1*40*2*EXAMPLE PAYER*****46*99999~
HL*1**20*1~
PRV*BI*PXC*207Q00000X~
NM1*85*2*SAMPLE FAMILY CLINIC*****XX*1234567893~
N3*100 MAIN STREET~
N4*ANYTOWN*TX*750010000~
REF*EI*123456789~
HL*2*1*22*0~
SBR*P*18*******CI~
NM1*IL*1*DOE*JOHN****MI*XYZ000000001~
N3*1 TEST LANE~
N4*ANYTOWN*TX*75001~
DMG*D8*19800101*M~
NM1*PR*2*EXAMPLE PAYER*****PI*99999~
CLM*CLAIM0001*125***11:B:1*Y*A*Y*Y~
HI*ABK:J069~
LX*1~
SV1*HC:99213*125*UN*1***1~
DTP*472*D8*20261120~
SE*24*0001~
GE*1*1~
IEA*1*000000001~

Now segment by segment.

Envelope and header

  • ISA: the interchange header. Sender and receiver IDs are padded to exactly 15 characters. T in ISA15 means test; production files use P. Control number 000000001.
  • GS*HC*...*005010X222A1: a functional group of health care claims (HC). The last element names the implementation guide version: 005010X222A1 is the 5010 professional claim.
  • ST*837*0001*005010X222A1: start of the transaction set, control number 0001.
  • BHT*0019*00*BATCH0001*...*CH: beginning of hierarchical transaction. 00 means original, CH means chargeable (a claim, as opposed to an encounter report).

Loops 1000A and 1000B: who is sending, who is receiving

  • NM1*41*2*ACME BILLING SERVICE*****46*TGJ23: submitter name. NM1 is the generic “name” segment; the first element (41 = submitter) tells you which name it is. 2 means a non-person entity. You’ll see NM1 many times, and its qualifier is what tells you which loop you’re in.
  • PER*IC*...: submitter contact information.
  • NM1*40*2*EXAMPLE PAYER*****46*99999: receiver (40).

Loop 2000A: billing provider

  • HL*1**20*1: HL ID 1, no parent, level 20 (billing provider), has children.
  • PRV*BI*PXC*207Q00000X: provider taxonomy code (family medicine here).
  • NM1*85*2*SAMPLE FAMILY CLINIC*****XX*1234567893: billing provider (85), identified by NPI (XX).
  • N3 / N4: address. In 5010 the billing provider ZIP must be the full nine digits.
  • REF*EI*123456789: the provider’s tax ID (EI = employer identification number).

Loop 2000B: subscriber

  • HL*2*1*22*0: HL ID 2, parent is HL 1, level 22 (subscriber), no children. That 0 matters: it says the patient is the subscriber, so there is no 2000C patient loop in this file.
  • SBR*P*18*******CI: subscriber information. P = primary payer, 18 = the patient is the subscriber (“self”), CI = commercial insurance. Note the run of empty elements between 18 and CI; position matters, so empty elements still need their separators.
  • NM1*IL*1*DOE*JOHN****MI*XYZ000000001: insured (IL), a person (1), last name then first name, member ID (MI).
  • N3 / N4 / DMG: subscriber address and demographics (D8 = date format CCYYMMDD, then date of birth and gender).
  • NM1*PR*2*EXAMPLE PAYER*****PI*99999: the payer (PR) and its payer ID.

Loop 2300: the claim

  • CLM*CLAIM0001*125***11:B:1*Y*A*Y*Y: here’s the actual claim. CLAIM0001 is the patient control number, which is your identifier and the one that comes back on the 835 remittance, so make it unique and traceable. 125 is the total charge. 11:B:1 is a composite: place of service 11 (office), facility code qualifier B, claim frequency 1 (original). The Y/A/Y/Y flags cover provider signature, assignment of benefits and release of information.
  • HI*ABK:J069: diagnosis codes. ABK marks the principal ICD-10 diagnosis; the decimal point is dropped, so J06.9 becomes J069.

Loop 2400: service lines

  • LX*1: service line number 1.
  • SV1*HC:99213*125*UN*1***1: the professional service. HC:99213 is a CPT/HCPCS code (an established patient office visit), charge 125, unit basis UN, 1 unit, and a diagnosis pointer of 1 that points back to the first code in HI.
  • DTP*472*D8*20261120: date of service.

Trailers

  • SE*24*0001: 24 segments in this transaction set, counting ST and SE themselves, with the control number matching ST02.
  • GE*1*1: one transaction set in this group, control number matching GS06.
  • IEA*1*000000001: one functional group in this interchange, matching ISA13.

Notice how the line-item charges have to add up to the claim total (125 = 125). Payers check that, and so should you before you send anything.

Building a tiny tokenizer

Before you build loop objects, you need a reliable way to turn the raw text into segments and elements. This is the smallest version I’d trust: it reads delimiters from the ISA, tolerates line breaks between segments and never assumes * or ~.


public sealed record X12Delimiters(char Element, char Component, char Repetition, char Segment);

public sealed record Segment(string Id, string[] Elements)
{
    // X12 numbers elements from 1 (NM101, NM102...). Elements[0] is the segment ID.
    public string this[int index] => index < Elements.Length ? Elements[index] : "";
}

public static class X12Tokenizer
{
    public static X12Delimiters ReadDelimiters(string raw)
    {
        var start = raw.IndexOf("ISA", StringComparison.Ordinal);
        if (start < 0 || raw.Length < start + 106)
            throw new FormatException("Input does not start with a complete ISA segment.");

        var isa = raw.AsSpan(start, 106);
        return new X12Delimiters(
            Element: isa[3],
            Component: isa[104],
            Repetition: isa[82],
            Segment: isa[105]);
    }

    public static IEnumerable<Segment> Tokenize(string raw)
    {
        var d = ReadDelimiters(raw);

        foreach (var chunk in raw.Split(d.Segment))
        {
            // Many files put CR/LF after each terminator. Strip it unless
            // the terminator itself is a newline.
            var text = chunk.Trim('\r', '\n', ' ');
            if (text.Length == 0) continue;

            var elements = text.Split(d.Element);
            yield return new Segment(elements[0], elements);
        }
    }
}

With segments in hand, the HL parent pointers give you the tree almost for free:

var raw = File.ReadAllText("sample-837p.txt");
var segments = X12Tokenizer.Tokenize(raw).ToList();

var levelNames = new Dictionary<string, string>
{
    ["20"] = "Billing provider",
    ["22"] = "Subscriber",
    ["23"] = "Patient",
};

var depth = new Dictionary<string, int>();

foreach (var hl in segments.Where(s => s.Id == "HL"))
{
    var id = hl[1];
    var parent = hl[2];
    depth[id] = parent.Length == 0 ? 0 : depth[parent] + 1;

    var name = levelNames.GetValueOrDefault(hl[3], $"Level {hl[3]}");
    Console.WriteLine($"{new string(' ', depth[id] * 2)}HL {id}: {name}");
}

// Output for the sample file:
// HL 1: Billing provider
//   HL 2: Subscriber

From here, a real parser walks the segments in order and uses the HL segments plus the NM1 qualifiers (85, IL, PR…) to decide which loop each segment belongs to. That’s where a state machine or a small set of loop handlers comes in, and it’s a good topic for later in the series. For now, notice how little code it takes to go from line noise to a tree.

837P vs 837I vs 837D

There are three flavors, and the good news is that the envelope, delimiters and HL hierarchy are identical across all of them. What changes is mostly inside the claim and service-line loops:

837P (professional) 837I (institutional) 837D (dental)
Who sends it Physicians, clinics, labs Hospitals, skilled nursing, facilities Dental offices
Guide version 005010X222A1 005010X223A2 005010X224A2
CLM05 Place of service code (e.g. 11) Facility type code (e.g. 13 for hospital outpatient) Place of service code
Service line segment SV1 with CPT/HCPCS SV2 with revenue codes (plus optional HCPCS) SV3 with CDT codes, plus TOO for teeth
Extras Diagnosis pointers on each line Admission info, CL1, statement dates, condition and value codes Tooth numbers and surfaces, oral cavity areas

If you build your tokenizer and envelope handling once, you can reuse them for all three, and also for the 835, 999 and 277CA that come back. Only the loop logic is transaction-specific.

Gotchas

These are the ones that have cost me (or teammates) real time.

SE01 counts ST and SE. The segment count in SE01 includes the ST and SE segments themselves. Off-by-two errors here get the whole transaction set rejected, and the rejection message is rarely as clear as you’d hope. Compute the count when you write the file; never hard-code it.

Control numbers must pair up and should be unique. ISA13/IEA02, GS06/GE02 and ST02/SE02 must match. Many receivers also reject an ISA13 they’ve seen recently as a duplicate, so generate interchange control numbers from a persistent sequence, not from “1 every time”.

HL parent pointers and child codes have to agree. If HL04 says 1 (has children) but no child HL follows, or a child points at an HL ID that doesn’t exist, validators will reject the file. This bites hardest when you add the 2000C patient loop for dependents and forget to flip the subscriber’s HL04 from 0 to 1.

No trailing delimiters. NM1*IL*1*DOE*JOHN****MI*XYZ000000001 is right; adding an extra * before the terminator because the next optional element is empty is wrong. Empty elements in the middle keep their separators; empty elements at the end are dropped. If you generate segments by joining an array, trim trailing empty elements first.

ISA is fixed-width. Pad ISA06 and ISA08 to 15 characters, the authorization and security fields to 10. A string-join-based writer that works perfectly for every other segment will quietly produce an invalid ISA.

Test vs production. ISA15 is T or P. Sending a T file to a production endpoint (or the reverse) is easy to do and confusing to diagnose. Make it configuration, not a constant.

The implementation guide is not the whole story. The X12 implementation guide (often called the TR3) defines the standard. Every payer and clearinghouse then publishes a companion guide with their own extra rules: required REF segments, specific payer IDs, sender ID formats, file size limits. A file that passes generic validation can still be rejected by one payer. Keep payer-specific rules in configuration or a rules layer, not sprinkled through your writer.

Your text may contain delimiters. A provider name containing * or ~ will break the file. Sanitize free-text fields before writing, and choose delimiters that can’t occur in your data.

Acceptance is not payment. A 999 acknowledgment tells you the file was syntactically valid. It doesn’t mean the claim was accepted for adjudication (that’s the 277CA) or paid (that’s the 835). I’ll come back to the unhappy paths later in this series.

Wrapping up

  • Read delimiters from the ISA. Never hard-code *, ~ or :.
  • Think in envelopes and trees. ISA/GS/ST are nesting dolls with matching control numbers, and the HL segments are parent pointers that turn a flat list into a hierarchy.
  • Generate the counts and control numbers. SE01, GE01, IEA01 and the control numbers should be computed by your writer, never typed by hand.

Once you can read an 837, debugging a rejected claim stops being archaeology. You can open the file, find the HL, find the CLM and see exactly what was sent.