keypark is a consumer for a hospital ADT feed (HL7 v2 admit, transfer, discharge, update and cancel messages) that keeps every patient's messages in order without letting one failing message stall the feed. A message the bed system rejects parks its patient: the patient's later messages wait behind it while every other patient keeps flowing, and the committed offset never moves past work that is not finished. The repository contains the consumer, a minimal HL7 parser, a fake bed-management service with seeded faults, two conventional consumers to compare against, and a deterministic simulator that measures the difference on a synthetic three-day feed.
A bed-management system is fed from the EHR's ADT stream. When it rejects a message (a ward that is not mapped yet, a timeout), the usual consumers do one of two things:
- Block the partition and retry. Every other patient on that partition waits, so a ward mapping that is missing for twelve hours delays the bed status of unrelated patients by hours.
- Retry a few times, dead-letter the message and move on. The patient's later messages are applied without it. A discharge applied before the admit does nothing, the admit is replayed from the dead-letter queue later, and the bed shows an occupant who left hours ago, or whose admit was cancelled (a ghost bed).
A third failure sits underneath both: committing offsets past a message that is still being retried loses it silently if the process crashes.
keypark keeps the ordering guarantee per patient (the key) rather than per partition, and ties the commit to the oldest message that is still retrying or parked (a dead letter is durable in the queue, so the commit may pass it).
All data in this repository is synthetic: the feed generator (keypark.feed) is seeded and produces fictional patients, wards and messages.
flowchart LR
feed["ADT feed<br/>4 partitions keyed by patient id"] --> consumer["ParkingConsumer<br/>parse, classify, apply"]
consumer -->|apply| beds["Bed service<br/>idempotent by control id"]
beds -->|"ok"| state["Bed state"]
beds -->|"503, timeout, ward not mapped"| retry["Retry with backoff<br/>full jitter, simulated clock"]
retry -->|"success"| beds
retry -->|"max attempts, or poison at once"| dlq[("Dead-letter queue<br/>durable")]
retry -.->|"patient's later messages"| lot["Parking lot<br/>one queue per patient"]
dlq -.->|"operator replay or skip"| lot
lot -->|"in feed order once the head clears"| beds
consumer -->|"commit low-water mark only"| feed
state --> compare["Compare with the fault-free truth<br/>and with the blocking and skip-to-DLQ consumers"]
hl7.pyreads MSH, EVN, PID and PV1 (separators come from MSH-1 and MSH-2, escapes\F\ \S\ \T\ \R\ \E\are decoded) and raisesParseError(segment, field)for anything malformed.log.pyis an in-process partitioned log with offsets and a committed offset per partition.consumer.pyholdsParkingConsumer. A failed message becomes the head of its patient's lane; later messages for that patient queue behind it. Errors are Transient (retry), Dependency (retry with a longer cap) or Poison (dead-letter on the first attempt). Aftermax_attemptsthe head is dead-lettered and the patient stays parked until an operator callsreplay(control_id)orskip(control_id). The consumer commits the smallest offset of any retrying or parked message, or its read position when there is none.beds.pyapplies A01, A02, A03, A08 and A11 idempotently by control id. An A02 for an unknown patient places the patient at the new location; an A03 for an unknown patient is a no-op (the module docstring lists the rest). Faults come from a schedule that depends only on the seed and the message, so every consumer faces the same faults.naive.pyhasBlockingConsumer(retries until success, blocking the partition) andSkipToDlqConsumer(retries N times, dead-letters, continues).sim.pyruns a scenario (default_scenario.toml, read withtomllib) on a simulated clock, with operator actions and a crash followed by a restart from the committed offset.metrics.pycomputes ghost beds, out-of-order applications, latency percentiles and the dead-letter contents.
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
keypark simulate --consumer parked --seed 9 # also: blocking, skip
keypark dlq list --seed 9 --limit 5 # what is waiting if nobody intervenes
keypark dlq replay MSG000027 --seed 9 # replay one entry and show the effect
pytest -qA run is a pure function of the scenario, the consumer and the seed, so the CLI keeps no state between commands: dlq list re-runs the scenario with the operator's scheduled actions turned off, and dlq replay adds one replay once the feed is drained (an id that is not waiting in the queue exits with status 1; a malformed message fails again and the command says it is still waiting). A run takes a few seconds. --scenario path.toml replaces the default scenario.
The seeded feed has 4,000 patient encounters and 23,197 messages over three simulated days on four partitions: A01 17.2%, A02 20.5%, A03 13.8%, A08 45.3%, A11 3.2%. Injected faults: 3% of messages fail once (some as a timeout after the change was applied), ward ICU-B is not mapped for the first 12 hours, 12 messages are malformed, and the consumer crashes once partition 2 has read the message at feed position 9,000. The scenario replays the dead-letter queue at hour 13 and skips the poison messages at the end.
keypark simulate --consumer parked --seed 9
consumer parked
seed 9
messages_in_feed 23197
messages_applied 23185
dead_lettered 92
dlq_open_at_end 0
ghost_beds 0
out_of_order 0
patients_differing_from_truth 0
p50_latency_s 0.5
p95_latency_s 1.0
p95_latency_unaffected_s 1.0
keypark simulate --consumer blocking --seed 9
consumer blocking
seed 9
messages_in_feed 23197
messages_applied 23185
dead_lettered 12
dlq_open_at_end 0
ghost_beds 0
out_of_order 0
patients_differing_from_truth 0
p50_latency_s 0.6
p95_latency_s 21856.8
p95_latency_unaffected_s 21772.0
keypark simulate --consumer skip --seed 9
consumer skip
seed 9
messages_in_feed 23197
messages_applied 23185
dead_lettered 94
dlq_open_at_end 0
ghost_beds 35
out_of_order 73
patients_differing_from_truth 35
p50_latency_s 0.5
p95_latency_s 1.0
p95_latency_unaffected_s 1.0
Latency is simulated seconds from a message's arrival to its application. "Unaffected" means patients who never had an admit or transfer to ICU-B. The 12 messages the feed cannot parse are never applied, so every consumer applies 23,185 of 23,197. The blocking consumer applies the same messages in the right order but holds back the other patients on a blocked partition for hours; the skip-to-DLQ consumer is fast but ends with 35 patients shown in a bed that the truth says they do not occupy (24 discharged, 11 with a cancelled admit) and 73 out-of-order applications. The parking consumer's final state equals the truth (every well-formed message applied in feed order with no faults).
keypark dlq list --seed 9 --limit 5
control_id patient part offset error tries reason
MSG000027 P03787 0 9 dependency 12 WardNotMapped: ward ICU-B is not mapped yet
MSG000063 P03818 1 12 dependency 12 WardNotMapped: ward ICU-B is not mapped yet
MSG000095 P02946 1 19 dependency 12 WardNotMapped: ward ICU-B is not mapped yet
MSG000125 P02263 1 29 dependency 12 WardNotMapped: ward ICU-B is not mapped yet
MSG000134 P03870 1 35 dependency 12 WardNotMapped: ward ICU-B is not mapped yet
92 waiting
The poison entries sit in the same list with poison and one try, for example PID-3: patient identifier is empty.
keypark dlq replay MSG000027 --seed 9
replayed MSG000027 for patient P03787: dead-letter status is now resolved
patient before: None
patient after: ('cancelled', None, 'NAKAMURA', 'UMA')
messages applied for this patient: 2 of 2
- Park by key, not by partition. Ordering only matters within a patient, so a failure blocks that patient and nobody else. The cost is memory and bookkeeping: a lane per failing patient, and one outage (ICU-B) puts dozens of patients in lanes at once (92 dead letters in the seeded run). Ordering across different patients is not preserved, which is fine for a bed state that is a per-patient map but would not be for a feed with cross-patient constraints.
- The commit is the low-water mark, and dead letters are durable. The commit invariant is that it never passes a message that is neither applied nor durably dead-lettered, so it is the smallest offset of any retrying or parked message. A dead-lettered message is stored in the dead-letter queue, so the commit may pass it, and a restarted consumer rebuilds the parked lanes from the queue. The alternative, holding the commit at the oldest dead letter, would make the consumer re-read hours of traffic after every restart during an outage.
- Idempotency lives in the bed service. After a restart the consumer re-delivers everything from the committed offset, and a timeout can mean the change was applied. Applying by control id turns both into no-ops. This assumes the downstream system can deduplicate; one that cannot needs an outbox on the consumer side.
- Full jitter on a simulated clock. The delay before retry
n(counting from 0) isuniform(0, min(cap, base * 2**n))from a seededrandom.Random; dependency errors use a longer cap (600 s against 60 s). Full jitter gives up some average retry speed to avoid retries from many patients landing together when a ward is mapped. Because the clock is simulated, a run is exactly reproducible. - Operator actions are explicit. After
max_attemptsa message is not retried again until a person replays or skips it, so a problem that retries cannot fix does not spin, and a skipped message is an operator decision recorded in the queue rather than a silent loss. - "Offset 9,000" is a position in the whole feed. Each partition holds roughly 5,800 messages, so the scenario's crash (
after_seq = 9000on partition 2) triggers when partition 2 reads the first message whose position in the feed, across partitions, is 9,000 or later.
GITHUB_ACTIONS=true CI=true COLUMNS=80 pytest -q99 tests pass with no warnings (warnings are errors in pyproject.toml). They cover:
- the HL7 parser on ten hand-written messages (escapes, non-default separators and escape character, repeated identifiers, extra segments, one malformed PV1 that raises
ParseErrorfor PV1-3); - retry delays for base 1 s, cap 60 s, seed 9 against a committed list computed from the documented formula;
- the bed service's rules for each trigger event, idempotency and the seeded fault schedule;
- the parking consumer, the blocking consumer and the skip-to-DLQ consumer on hand-built feeds;
- four invariants under Hypothesis stateful testing (100 cases of random messages, fault schedules, crash points and operator actions): per-patient application order equals feed order, every consumed message is in exactly one of applied, retrying, parked or dead-lettered, the committed offset never passes a message that is neither applied nor durably dead-lettered (checked from the log, the bed service and the dead-letter queue, not from the consumer's own bookkeeping), and after a drain the bed state equals the fault-free state;
- the whole seeded feed: at least 5 ghost beds and 20 out-of-order applications for skip-to-DLQ, none for the parking consumer, blocking p95 above one hour for unaffected patients against a parking p95 within 10% of the fault-free run and no unaffected, well-formed patient delayed past a minute, a crash and restart (after position 9,000, and again during the ICU-B outage) that ends in the fault-free state with no message applied twice, and poison messages that stay at one attempt and keep their patient parked until skipped;
- the CLI output.
src/keypark/
hl7.py HL7 v2 parser and writer for ADT messages
log.py partitioned log with committed offsets
dlq.py durable dead-letter queue
policy.py retry policy and backoff formula
errors.py transient, dependency and poison error classes
clock.py simulated clock
consumer.py ParkingConsumer and the shared consumer mechanics
naive.py BlockingConsumer and SkipToDlqConsumer
beds.py fake bed-management service and fault schedule
feed.py seeded feed generator
scenario.py scenario TOML loader
default_scenario.toml the three-day scenario
sim.py deterministic runner
metrics.py ghost beds, ordering, latency
cli.py keypark command
tests/ unit, stateful and whole-feed tests, fixtures/adt_samples.hl7
MIT. See LICENSE.
