A backend that ingests X12 835 electronic remittance advice files, checks that they balance, posts payments and adjustments per claim and service line, routes denials by CARC code to a work queue, and reassociates each ERA with the EFT deposit that paid it.

A clinic or billing company gets paid by each payer twice over: money lands in the bank by EFT, and an 835 file explains which claims it covers and why each claim was paid less than billed. Posting those payments by hand does not scale past a few hundred claims a week.
This guide builds the backend that parses 835s, posts payments, queues denials and matches each file to its deposit.
An 835 is a set of segments separated by a terminator, usually ~, with elements separated by *. The separators are defined by the fixed-width ISA envelope at the start. The segments a posting system needs:
ACH for an EFT or CHK for a paper check.The CMS remittance advice page explains how group codes assign responsibility: CO amounts belong to the provider, and only PR amounts can be billed to a Medicare patient.
For each claim, the charge minus every claim-level and line-level adjustment equals the payment. For the whole file, the sum of claim payments minus the provider-level adjustments equals BPR02, and between them these two rules catch most corrupt or misparsed files. A file that fails either rule should be rejected before anything is posted, since partially posting it leaves the ledger out of step with the deposit.
Amounts are decimals with up to two places, and some payers send negative amounts on reversals. Parse them into integer cents, never floats.
The parser below reads the separators from ISA, walks the segments and keeps track of the current claim and service line, so each CAS segment is attached to the right level. It only collects what posting needs and ignores the rest:
// remits/parse.go
package remits
import (
"bufio"
"errors"
"fmt"
"math/big"
"strings"
)
// Cents parses an X12 decimal amount such as "1250.5" or "-30" into cents.
func Cents(s string) (int64, error) {
if s == "" {
return 0, nil
}
r, ok := new(big.Rat).SetString(s)
if !ok {
return 0, fmt.Errorf("bad amount %q", s)
}
r.Mul(r, big.NewRat(100, 1))
if !r.IsInt() {
return 0, fmt.Errorf("amount %q has more than two decimals", s)
}
return r.Num().Int64(), nil
}
type Adjustment struct {
Group string // CO, PR, OA, PI
Reason string // CARC, for example 45 or 97
Cents int64
}
type ServiceLine struct {
Procedure string // SVC01, for example HC:99213
ChargeCents int64
PaidCents int64
Adjustments []Adjustment
}
type ClaimPayment struct {
PatientControlNumber string // CLP01, your claim ID
Status string // CLP02: 1, 2, 3, 4 (denied), 22 (reversal) ...
ChargeCents int64
PaidCents int64
PatientRespCents int64
PayerClaimNumber string // CLP07
Adjustments []Adjustment
Lines []ServiceLine
}
type ProviderAdjustment struct {
Reason string // PLB03-1, for example WO or L6
Cents int64
}
type Remittance struct {
PaymentCents int64 // BPR02
Method string // BPR04: ACH, CHK, NON ...
TraceNumber string // TRN02, matches the EFT or check number
PayerID string // TRN03
Claims []ClaimPayment
ProviderAdjs []ProviderAdjustment
}
// Parse reads one 835 transaction. Separators come from the ISA segment.
func Parse(raw string) (*Remittance, error) {
raw = strings.TrimLeft(raw, " \r\n\t")
if len(raw) < 106 || !strings.HasPrefix(raw, "ISA") {
return nil, errors.New("missing ISA segment")
}
elem := string(raw[3])
comp := string(raw[104])
segTerm := raw[105]
r := &Remittance{}
var claim *ClaimPayment
var line *ServiceLine
sc := bufio.NewScanner(strings.NewReader(raw))
sc.Buffer(make([]byte, 1<<20), 1<<26)
sc.Split(func(data []byte, atEOF bool) (int, []byte, error) {
for i, b := range data {
if b == segTerm {
return i + 1, data[:i], nil
}
}
if atEOF && len(data) > 0 {
return len(data), data, nil
}
return 0, nil, nil
})
for sc.Scan() {
seg := strings.TrimSpace(sc.Text())
if seg == "" {
continue
}
f := strings.Split(seg, elem)
get := func(i int) string {
if i < len(f) {
return f[i]
}
return ""
}
var err error
switch f[0] {
case "BPR":
r.Method = get(4)
r.PaymentCents, err = Cents(get(2))
case "TRN":
r.TraceNumber, r.PayerID = get(2), get(3)
case "CLP":
r.Claims = append(r.Claims, ClaimPayment{
PatientControlNumber: get(1),
Status: get(2),
PayerClaimNumber: get(7),
})
claim, line = &r.Claims[len(r.Claims)-1], nil
if claim.ChargeCents, err = Cents(get(3)); err == nil {
if claim.PaidCents, err = Cents(get(4)); err == nil {
claim.PatientRespCents, err = Cents(get(5))
}
}
case "SVC":
if claim == nil {
return nil, errors.New("SVC before CLP")
}
claim.Lines = append(claim.Lines, ServiceLine{Procedure: get(1)})
line = &claim.Lines[len(claim.Lines)-1]
if line.ChargeCents, err = Cents(get(2)); err == nil {
line.PaidCents, err = Cents(get(3))
}
case "CAS":
if claim == nil {
return nil, errors.New("CAS before CLP")
}
// CAS can carry up to six reason, amount, quantity triplets.
for i := 2; i+1 < len(f) && i <= 17; i += 3 {
if get(i) == "" {
continue
}
c, cerr := Cents(get(i + 1))
if cerr != nil {
return nil, cerr
}
adj := Adjustment{Group: get(1), Reason: get(i), Cents: c}
if line != nil {
line.Adjustments = append(line.Adjustments, adj)
} else {
claim.Adjustments = append(claim.Adjustments, adj)
}
}
case "PLB":
// PLB03 onward: pairs of reason composite and amount.
for i := 3; i+1 < len(f); i += 2 {
c, cerr := Cents(get(i + 1))
if cerr != nil {
return nil, cerr
}
reason, _, _ := strings.Cut(get(i), comp)
r.ProviderAdjs = append(r.ProviderAdjs, ProviderAdjustment{Reason: reason, Cents: c})
}
case "SE":
claim, line = nil, nil
}
if err != nil {
return nil, fmt.Errorf("%s segment: %w", f[0], err)
}
}
return r, sc.Err()
}
// Check verifies the two balancing rules an 835 must satisfy.
func Check(r *Remittance) []string {
var problems []string
var paid, plb int64
for _, c := range r.Claims {
paid += c.PaidCents
adj := int64(0)
for _, a := range c.Adjustments {
adj += a.Cents
}
for _, l := range c.Lines {
for _, a := range l.Adjustments {
adj += a.Cents
}
}
if c.ChargeCents-adj != c.PaidCents {
problems = append(problems, fmt.Sprintf("claim %s: charge %d minus adjustments %d is not paid %d",
c.PatientControlNumber, c.ChargeCents, adj, c.PaidCents))
}
}
for _, p := range r.ProviderAdjs {
plb += p.Cents
}
if paid-plb != r.PaymentCents {
problems = append(problems, fmt.Sprintf("claims paid %d minus provider adjustments %d is not BPR02 %d",
paid, plb, r.PaymentCents))
}
return problems
}
A test with a three-claim sample (one paid with a coinsurance and a fee schedule reduction, one denied with CARC 16, one with a bundled line and a provider-level adjustment) balances to the cent, and changing one claim's payment makes both rules fail.
Encore is a backend framework with built-in infrastructure, and the remittance service declares its Postgres database, a Pub/Sub topic for denials and a cron job for unmatched ERAs in its own code, and Encore provisions them in your own AWS or GCP account.

Run in your terminal to get started locally.
The schema keeps the remittance, each claim payment and every adjustment, plus the denial work queue:
-- remits/migrations/1_remits.up.sql
CREATE TABLE remittances (
id BIGSERIAL PRIMARY KEY,
payer_id TEXT NOT NULL,
trace_number TEXT NOT NULL,
method TEXT NOT NULL,
payment_cents BIGINT NOT NULL,
received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
deposit_id TEXT,
matched_at TIMESTAMPTZ,
UNIQUE (payer_id, trace_number)
);
CREATE TABLE claim_payments (
id BIGSERIAL PRIMARY KEY,
remittance_id BIGINT NOT NULL REFERENCES remittances(id),
patient_control_number TEXT NOT NULL,
payer_claim_number TEXT NOT NULL,
status TEXT NOT NULL,
charge_cents BIGINT NOT NULL,
paid_cents BIGINT NOT NULL,
patient_resp_cents BIGINT NOT NULL
);
CREATE TABLE adjustments (
id BIGSERIAL PRIMARY KEY,
claim_payment_id BIGINT NOT NULL REFERENCES claim_payments(id),
procedure TEXT, -- NULL for claim-level adjustments
group_code TEXT NOT NULL,
reason_code TEXT NOT NULL,
amount_cents BIGINT NOT NULL
);
CREATE TABLE denial_tasks (
claim_payment_id BIGINT PRIMARY KEY REFERENCES claim_payments(id),
reason_codes TEXT[] NOT NULL,
status TEXT NOT NULL DEFAULT 'open',
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX ON remittances (received_at) WHERE matched_at IS NULL;
The ingest endpoint parses, checks the balance and posts the whole file in one transaction. The UNIQUE (payer_id, trace_number) constraint makes a resent file a no-op, and denials are published after the commit:
// remits/remits.go
package remits
import (
"context"
"errors"
"strings"
"encore.dev/beta/errs"
"encore.dev/pubsub"
"encore.dev/rlog"
"encore.dev/storage/sqldb"
)
var db = sqldb.NewDatabase("remits", sqldb.DatabaseConfig{Migrations: "./migrations"})
type ClaimDenied struct {
ClaimPaymentID int64 `json:"claim_payment_id"`
PatientControl string `json:"patient_control_number"`
ReasonCodes []string `json:"reason_codes"`
}
var Denials = pubsub.NewTopic[*ClaimDenied]("claim-denied", pubsub.TopicConfig{
DeliveryGuarantee: pubsub.AtLeastOnce,
})
type IngestParams struct {
X12 string `json:"x12"`
}
type IngestResponse struct {
RemittanceID int64 `json:"remittance_id"`
Claims int `json:"claims"`
Duplicate bool `json:"duplicate"`
}
//encore:api private method=POST path=/remits/ingest
func Ingest(ctx context.Context, p *IngestParams) (*IngestResponse, error) {
r, err := Parse(p.X12)
if err != nil {
return nil, errs.B().Code(errs.InvalidArgument).Msg(err.Error()).Err()
}
if problems := Check(r); len(problems) > 0 {
return nil, errs.B().Code(errs.FailedPrecondition).Msg("835 does not balance: " + strings.Join(problems, "; ")).Err()
}
tx, err := db.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback()
var remitID int64
err = tx.QueryRow(ctx, `
INSERT INTO remittances (payer_id, trace_number, method, payment_cents)
VALUES ($1, $2, $3, $4)
ON CONFLICT (payer_id, trace_number) DO NOTHING
RETURNING id
`, r.PayerID, r.TraceNumber, r.Method, r.PaymentCents).Scan(&remitID)
if errors.Is(err, sqldb.ErrNoRows) {
return &IngestResponse{Duplicate: true}, nil
} else if err != nil {
return nil, err
}
var denied []*ClaimDenied
for _, c := range r.Claims {
var claimID int64
err := tx.QueryRow(ctx, `
INSERT INTO claim_payments (remittance_id, patient_control_number, payer_claim_number,
status, charge_cents, paid_cents, patient_resp_cents)
VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id
`, remitID, c.PatientControlNumber, c.PayerClaimNumber, c.Status,
c.ChargeCents, c.PaidCents, c.PatientRespCents).Scan(&claimID)
if err != nil {
return nil, err
}
var reasons []string
insert := func(procedure *string, a Adjustment) error {
if a.Group == "CO" {
reasons = append(reasons, a.Group+"-"+a.Reason)
}
_, err := tx.Exec(ctx, `
INSERT INTO adjustments (claim_payment_id, procedure, group_code, reason_code, amount_cents)
VALUES ($1, $2, $3, $4, $5)
`, claimID, procedure, a.Group, a.Reason, a.Cents)
return err
}
for _, a := range c.Adjustments {
if err := insert(nil, a); err != nil {
return nil, err
}
}
zeroLine := false
for _, l := range c.Lines {
proc := l.Procedure
for _, a := range l.Adjustments {
if err := insert(&proc, a); err != nil {
return nil, err
}
}
zeroLine = zeroLine || (l.PaidCents == 0 && l.ChargeCents > 0)
}
if c.Status == "4" || (zeroLine && len(reasons) > 0) {
// The task row commits with the payments, so a failed publish cannot lose it.
if _, err := tx.Exec(ctx, `
INSERT INTO denial_tasks (claim_payment_id, reason_codes) VALUES ($1, $2)
ON CONFLICT (claim_payment_id) DO NOTHING`, claimID, reasons); err != nil {
return nil, err
}
denied = append(denied, &ClaimDenied{ClaimPaymentID: claimID, PatientControl: c.PatientControlNumber, ReasonCodes: reasons})
}
}
if err := tx.Commit(); err != nil {
return nil, err
}
for _, d := range denied {
if _, err := Denials.Publish(ctx, d); err != nil {
rlog.Error("publish denial failed", "claim_payment_id", d.ClaimPaymentID, "err", err)
}
}
return &IngestResponse{RemittanceID: remitID, Claims: len(r.Claims)}, nil
}
Only CO reasons go on the denial task, since PR amounts are patient balances and belong in patient billing, not appeals. The denial task is written in the same transaction as the payments, so it exists even if the publish after commit fails. That failure is logged rather than returned, and the subscriber below inserts the same row, which is a no-op when it already exists.
// remits/followup.go
package remits
import (
"context"
"encore.dev/beta/errs"
"encore.dev/cron"
"encore.dev/pubsub"
"encore.dev/rlog"
)
var _ = pubsub.NewSubscription(Denials, "open-denial-task", pubsub.SubscriptionConfig[*ClaimDenied]{
Handler: func(ctx context.Context, d *ClaimDenied) error {
// The primary key makes a redelivered message a no-op.
_, err := db.Exec(ctx, `
INSERT INTO denial_tasks (claim_payment_id, reason_codes) VALUES ($1, $2)
ON CONFLICT (claim_payment_id) DO NOTHING
`, d.ClaimPaymentID, d.ReasonCodes)
return err
},
})
type DepositParams struct {
DepositID string `json:"deposit_id"`
PayerID string `json:"payer_id"` // from the ACH originator, mapped by the bank feed
TraceNumber string `json:"trace_number"`
AmountCents int64 `json:"amount_cents"`
}
type DepositResponse struct {
RemittanceID int64 `json:"remittance_id"`
}
// RecordDeposit is called by the bank feed integration for each EFT credit.
//
//encore:api private method=POST path=/remits/deposits
func RecordDeposit(ctx context.Context, p *DepositParams) (*DepositResponse, error) {
var id int64
err := db.QueryRow(ctx, `
UPDATE remittances SET deposit_id = $1, matched_at = now()
WHERE payer_id = $4 AND trace_number = $2 AND payment_cents = $3 AND matched_at IS NULL
RETURNING id
`, p.DepositID, p.TraceNumber, p.AmountCents, p.PayerID).Scan(&id)
if err != nil {
return nil, errs.B().Code(errs.NotFound).Msg("no unmatched ERA for this trace number and amount").Err()
}
return &DepositResponse{RemittanceID: id}, nil
}
var _ = cron.NewJob("unmatched-eras", cron.JobConfig{
Title: "Report ERAs without a matching deposit",
Schedule: "0 6 * * *",
Endpoint: ReportUnmatched,
})
//encore:api private
func ReportUnmatched(ctx context.Context) error {
rows, err := db.Query(ctx, `
SELECT payer_id, trace_number, payment_cents FROM remittances
WHERE matched_at IS NULL AND method = 'ACH' AND received_at < now() - interval '3 days'
`)
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var payer, trace string
var cents int64
if err := rows.Scan(&payer, &trace, ¢s); err != nil {
return err
}
rlog.Warn("ERA without deposit", "payer_id", payer, "trace_number", trace, "payment_cents", cents)
}
return rows.Err()
}
The payer, trace number and amount together identify the deposit, which protects against a payer reusing a trace number across files and against two payers sending the same trace number. Payers usually put the TRN02 value in the CCP+ addenda record of the ACH credit, and the CAQH CORE operating rules ask health plans to release the ERA within three business days of the EFT, which is where the three-day window in the report comes from.
encore run starts Postgres, applies the migration and runs the denial subscription on your machine, so posting a sample 835 to the ingest endpoint shows the claim rows and a denial task in the local dashboard. The unmatched report is an Encore platform Managed cron job that runs in deployed environments, not locally or in preview environments, so call ReportUnmatched from the local dashboard to test it. Remittances contain patient identifiers, so keep access to the database and logs limited to the billing team, and log claim IDs rather than patient names, as the PHI audit log guide describes.
A coding agent adding a new rule, for example routing CARC 16 to a different team than CARC 97, changes the subscription handler and tests it against a sample file locally in the same change, with no queue to create first.
Best fit: Health tech companies, billing services and provider groups that want ERA posting, denial follow-up and deposit matching in one service in their own AWS or GCP account.
An 835 is the X12 Health Care Claim Payment/Advice transaction, also called an electronic remittance advice or ERA. A payer sends it to explain a payment: which claims it covers, what was paid per claim and service line, and why the rest was adjusted, using group codes and claim adjustment reason codes.
CO is a contractual obligation, an amount the provider writes off under its payer contract, and PR is patient responsibility, such as a deductible, coinsurance or copay that can be billed to the patient. OA and PI cover other adjustments and payer-initiated reductions.
Match on the TRN02 trace number and the BPR02 amount. For an EFT, the payer puts the same trace number in the ACH CCP+ addenda record that accompanies the deposit, so finding that trace number and amount in the bank feed reassociates the remittance with the money.
Yes. Encore deploys the remittance service, its Postgres database, the denial queue and the reassociation cron job to your own AWS or GCP account, so remittance data stays in infrastructure you control.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.