On this page
A patient-facing platform in front of more than one EHR is one of the most common briefs in provider IT. A health network has grown by acquisition, its hospitals run one EHR and its clinics another, and patients are expected to use a separate portal for each. The brief is a single front door: one sign-in, one place to book, message and join a video visit, with the EHRs remaining the systems of record.
This article sets out a reference architecture for that platform on Azure, for an organisation regulated under HIPAA. It then goes deep on the path with the most ways to go wrong, which is booking an appointment: one slot, many patients, and an EHR on the far side that may be slow, unavailable, or asked the same thing twice. That path is implemented in .NET 8 and tested in the accompanying sample. The rest of the platform is described at the level a design review needs.
Software is not “HIPAA compliant” on its own. The Security Rule places obligations on the covered entity and its business associates: a risk analysis, administrative and physical safeguards, and the technical safeguards in 45 CFR 164.312. A design can make those safeguards straightforward to implement and to evidence. It cannot substitute for the risk analysis, the policies or the business associate agreements, including the one with the cloud provider.
Problem and constraints
The functional scope is familiar: registration and sign-in, provider search and appointment booking across facilities, reminders, secure messaging, video visits, and a view of results and visit summaries drawn from the EHRs. The constraints are what shape the architecture.
| Constraint | Consequence for the design |
|---|---|
| The EHRs stay the systems of record for clinical data and for the schedule | The platform stores references and its own transactional state. It does not become a third copy of the chart |
| Two EHRs with different integration interfaces | Vendor differences are confined to adapters behind one internal contract |
| The certified EHR API is a read API | Reading a patient’s data over FHIR R4 is standard. Writing an appointment is not part of that criterion and is arranged with each vendor |
| An EHR will be unavailable at times, for maintenance if nothing else | Patient-facing functions must not depend on a synchronous call to the EHR succeeding |
| Front-desk staff book into the same schedule from inside the EHR | Somebody has to own each slot. This is the decision the next section turns on |
| HIPAA Security Rule | Unique identities, audit controls, integrity and transmission security are designed in, and PHI is kept out of logs, caches and URLs |
The third row deserves a note, because it is where designs most often assume too much. The certification criterion behind the standard EHR API in the United States, 170.315(g)(10), requires the API to respond to requests for patient data, for one patient and in bulk. It does not require the EHR to accept an appointment created by a third party. Scheduling has its own guidance, notably the Argonaut Scheduling guide, and each vendor exposes it in its own way and under its own agreement. An architecture slide that says “POST Appointment to the EHR” is a commercial and technical dependency to be confirmed in each vendor’s sandbox before anything is built on it.
Architecture overview

%%{init: {'theme':'base','themeVariables':{'primaryColor':'#FFF3E0','primaryTextColor':'#232F3E','primaryBorderColor':'#FF9900','lineColor':'#232F3E','clusterBkg':'#F8FAFC','clusterBorder':'#CBD5E1','edgeLabelBackground':'#FFFFFF','nodeTextColor':'#232F3E'}}}%%
flowchart TD
A["Patient app
web and mobile"] --> ID["Microsoft Entra External ID
sign-in and MFA"]
A --> G["Azure API Management
token validation, rate limits"]
G --> B["Booking service
.NET"]
G --> T["Telehealth and notification services"]
B --> DB[("Azure SQL
slots, appointments, outbox")]
DB --> O["Outbox dispatcher
circuit breaker for each EHR"]
O --> AD["EHR adapters
one for each vendor interface"]
AD --> E1["EHR A
main hospitals"]
AD --> E2["EHR B
clinics"]
B --> AU["Audit trail
append-only, identifiers only"]
O --> AU
classDef compute fill:#FFF3E0,stroke:#FF9900,stroke-width:2px,color:#232F3E
classDef db fill:#EBF8FF,stroke:#0073BB,stroke-width:2px,color:#004C74
classDef edge fill:#F3E8FF,stroke:#7C3AED,stroke-width:2px,color:#4C1D95
classDef store fill:#F0FFF4,stroke:#1D8102,stroke-width:2px,color:#145202
classDef alert fill:#FEF2F2,stroke:#D13212,stroke-width:2px,color:#991B1B
class B,T,O,AD compute
class DB,E1,E2 db
class ID,G edge
class A store
class AU alert| Element | Azure service | Why |
|---|---|---|
| Patient identity | Microsoft Entra External ID | Customer identity with MFA and standard OpenID Connect. Azure AD B2C has not been available to new customers since 1 May 2025, though Microsoft supports existing tenants until at least May 2030 |
| API front door | Azure API Management | Token validation, throttling and a single place for API versioning. It routes FHIR traffic like any other HTTP API; the FHIR logic lives in the services |
| Services | Azure Container Apps or AKS | Stateless .NET services scaled on HTTP load, with the dispatcher scaled on queue depth |
| Transactional store | Azure SQL Database | Slots, appointments and the outbox need one ACID transaction. Sensitive columns can use Always Encrypted |
| Messaging | Azure Service Bus | Carries events to notifications and other consumers, with duplicate detection on the event id |
| Secrets and keys | Azure Key Vault with managed identities | No connection strings or EHR client secrets in configuration |
| Monitoring | Azure Monitor and Microsoft Defender for Cloud | Metrics and traces that carry identifiers only, and posture management for the subscription |
Slot ownership
Every other decision follows from this one. A slot can be taken by a patient in the portal or by a receptionist in the EHR, and those are two different systems.
| Option | How it works | Strength | Weakness |
|---|---|---|---|
| The EHR owns every slot | The portal calls the EHR’s booking interface synchronously and shows the patient the answer | One authority, so no double booking between portal and front desk | Booking is down whenever the EHR is, and depends on the vendor offering a booking interface with concurrency control |
| The platform owns an allocation | The EHR releases a block of slots for online booking. The platform decides who gets each one and reports the result to the EHR | Booking keeps working through an EHR outage, and the platform controls concurrency | Two systems of record for a short time. Needs reconciliation and an agreed rule for the allocation |
| The platform keeps a copy and hopes | Slots are cached from the EHR and booked optimistically, with the EHR write as a later step | Simple to build | Double bookings between portal and front desk, discovered by the patient |
The reference design takes the second option, which matches a common way of running online booking: a defined set of online-bookable slots. The first option is sound where the vendor interface supports it, and the sample shows the FHIR mechanism it relies on. The third is the one to recognise and refuse. It tends to arrive disguised as a performance optimisation.
Booking flow
A booking has to be correct under two kinds of pressure: many patients wanting the same slot at once, and one patient’s request arriving more than once because a phone lost signal and the app retried. A pattern that turns up often in first drafts handles neither. It checks a cache to see whether the slot is free, then writes the booking, then updates the cache. Two requests can both pass the check before either writes. A check followed by a write is not a lock, whatever the comment above it says.
The decision belongs in the database, in one transaction, as a conditional update. If the update changes no row, somebody else has the slot.
namespace Booking.Core;
public enum BookingStatus { Booked, SlotTaken, UnknownSlot }
public sealed record BookingResult(BookingStatus Status, string? AppointmentId);
/// <summary>What the platform asks the EHR to record. References only: no names, no dates of birth.</summary>
public sealed record AppointmentEvent(string AppointmentId, string SlotId, string PatientReference, DateTimeOffset RecordedAt);
/// <summary>
/// The platform's own record of who holds which slot. Booking a slot, writing the appointment and writing the
/// outbox event are one atomic step, so there is never a booked slot with no event, or an event with no booking.
///
/// This class keeps its state in memory behind one lock so the sample runs anywhere. In a deployment the same
/// three writes are one database transaction:
/// UPDATE slot SET status = 'busy' WHERE slot_id = @slot AND status = 'free' -- zero rows means "taken"
/// INSERT INTO appointment ...; INSERT INTO outbox ...; COMMIT
/// The conditional UPDATE is the lock. A cache in front of it is an optimisation and never the decision.
/// </summary>
public sealed class BookingLedger(IEnumerable<string> freeSlots, TimeProvider clock)
{
private readonly object _transaction = new();
private readonly HashSet<string> _free = new(freeSlots, StringComparer.Ordinal);
private readonly HashSet<string> _known = new(freeSlots, StringComparer.Ordinal);
private readonly Dictionary<string, BookingResult> _byIdempotencyKey = new(StringComparer.Ordinal);
private readonly List<AppointmentEvent> _outbox = [];
private readonly HashSet<string> _delivered = new(StringComparer.Ordinal);
private int _sequence;
/// <summary>
/// Books a slot for a patient. The same idempotency key always gets the answer the first call got, so a
/// client that timed out and retried cannot book twice or be told "taken" about its own booking.
/// </summary>
public BookingResult Book(string slotId, string patientReference, string idempotencyKey)
{
ArgumentException.ThrowIfNullOrWhiteSpace(slotId);
ArgumentException.ThrowIfNullOrWhiteSpace(patientReference);
ArgumentException.ThrowIfNullOrWhiteSpace(idempotencyKey);
lock (_transaction)
{
if (_byIdempotencyKey.TryGetValue(idempotencyKey, out BookingResult? earlier))
{
return earlier;
}
BookingResult result;
if (!_known.Contains(slotId))
{
result = new BookingResult(BookingStatus.UnknownSlot, null);
}
else if (!_free.Remove(slotId))
{
result = new BookingResult(BookingStatus.SlotTaken, null);
}
else
{
string appointmentId = $"appt-{++_sequence:D6}";
_outbox.Add(new AppointmentEvent(appointmentId, slotId, patientReference, clock.GetUtcNow()));
result = new BookingResult(BookingStatus.Booked, appointmentId);
}
_byIdempotencyKey[idempotencyKey] = result;
return result;
}
}
/// <summary>Events not yet confirmed by the EHR, oldest first.</summary>
public IReadOnlyList<AppointmentEvent> PendingEvents()
{
lock (_transaction)
{
return _outbox.Where(e => !_delivered.Contains(e.AppointmentId)).ToList();
}
}
public void MarkDelivered(string appointmentId)
{
lock (_transaction)
{
_delivered.Add(appointmentId);
}
}
}The class holds its state in memory behind a single lock so that the sample runs anywhere, and the comment gives the SQL it stands for. Three properties carry over to the real thing.
- The conditional update is the only arbiter. A cache can make the list of free slots fast to display. It is never consulted to decide who gets one.
- The outbox event is written with the booking. There is no moment at which a slot is booked and the instruction to tell the EHR does not exist, or the reverse.
- The idempotency key is stored with the result. A retried request receives the answer its first attempt received. Without this, a patient whose first request succeeded and whose retry arrived a second later would be told that their own slot was taken.
EHR integration
The patient has an answer as soon as the transaction commits. The EHR learns of the booking a moment later, from a dispatcher that reads the outbox. Delivery is at least once: an event leaves the outbox only when the EHR has confirmed it, so a lost response means the event is sent again.
%%{init: {'theme':'base','themeVariables':{'primaryColor':'#FFF3E0','primaryTextColor':'#232F3E','primaryBorderColor':'#FF9900','lineColor':'#232F3E','signalColor':'#0073BB','signalTextColor':'#0F172A','actorBkg':'#FFF3E0','actorBorder':'#FF9900','actorTextColor':'#232F3E','noteBkgColor':'#FFF8E7','noteBorderColor':'#FF9900','noteTextColor':'#232F3E'}}}%%
sequenceDiagram
participant P as Patient app
participant B as Booking service
participant O as Outbox dispatcher
participant E as EHR
P->>B: POST booking, Idempotency-Key
B->>B: One transaction, slot busy, appointment, outbox event
B-->>P: 201 Booked
O->>E: POST Appointment, If-None-Exist identifier
E--xO: Timeout, the response is lost
Note over O: The event stays in the outbox
O->>E: POST Appointment, If-None-Exist identifier
E-->>O: 200 OK, already present
Note over O: The event is marked deliverednamespace Booking.Core;
public interface IEhrGateway
{
/// <summary>
/// Records the appointment in the EHR. Must be safe to call more than once for the same event:
/// delivery is at least once, so the gateway is where "exactly once" has to be made true.
/// </summary>
Task<EhrOutcome> RecordAppointmentAsync(AppointmentEvent appointment, CancellationToken cancellationToken);
}
public sealed record EhrOutcome(bool Created, string EhrAppointmentId);
public sealed record DispatchReport(int Delivered, int Failed, int SkippedCircuitOpen);
/// <summary>
/// Moves booked appointments from the outbox to the EHR. An event leaves the outbox only after the EHR has
/// confirmed it. A failure leaves it in place for the next pass, and a failing EHR opens the circuit.
/// </summary>
public sealed class OutboxDispatcher(BookingLedger ledger, IEhrGateway ehr, CircuitBreaker breaker, AuditLog audit)
{
public async Task<DispatchReport> DispatchPendingAsync(CancellationToken cancellationToken = default)
{
int delivered = 0, failed = 0, skipped = 0;
foreach (AppointmentEvent appointment in ledger.PendingEvents())
{
if (!breaker.TryEnter())
{
skipped++;
continue;
}
try
{
EhrOutcome outcome = await ehr.RecordAppointmentAsync(appointment, cancellationToken).ConfigureAwait(false);
breaker.RecordSuccess();
ledger.MarkDelivered(appointment.AppointmentId);
audit.Record("system/ehr-sync", outcome.Created ? "ehr.appointment.created" : "ehr.appointment.already-present", appointment.AppointmentId);
delivered++;
}
catch (Exception error) when (error is (HttpRequestException or TimeoutException or TaskCanceledException) && !cancellationToken.IsCancellationRequested)
{
breaker.RecordFailure();
audit.Record("system/ehr-sync", "ehr.appointment.failed", appointment.AppointmentId);
failed++;
}
}
return new DispatchReport(delivered, failed, skipped);
}
}At-least-once delivery moves the problem to the receiving side: the second delivery must not create a second appointment. On a FHIR R4 interface the tool for this is a conditional create. The platform’s appointment id is sent as a business identifier and as the If-None-Exist condition. If no Appointment carries that identifier, the server creates one and returns 201. If one does, the server creates nothing and returns 200.
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Booking.Core;
/// <summary>
/// Records an appointment on a FHIR R4 server with a conditional create. The platform's appointment id is
/// sent as a business identifier and as the If-None-Exist condition, so a second delivery of the same event
/// matches the first and creates nothing. This is the generic R4 interaction; an EHR that exposes booking as
/// an operation instead of a create needs its own implementation of <see cref="IEhrGateway"/>.
/// </summary>
public sealed class FhirEhrGateway(HttpClient http, string identifierSystem) : IEhrGateway
{
private static readonly MediaTypeHeaderValue FhirJson = new("application/fhir+json");
public async Task<EhrOutcome> RecordAppointmentAsync(AppointmentEvent appointment, CancellationToken cancellationToken)
{
using HttpRequestMessage request = new(HttpMethod.Post, "Appointment");
request.Headers.Accept.ParseAdd("application/fhir+json");
request.Headers.TryAddWithoutValidation("If-None-Exist", $"identifier={Uri.EscapeDataString(identifierSystem)}|{Uri.EscapeDataString(appointment.AppointmentId)}");
request.Content = new StringContent(ToFhir(appointment, identifierSystem).ToJsonString(), Encoding.UTF8);
request.Content.Headers.ContentType = FhirJson;
using HttpResponseMessage response = await http.SendAsync(request, cancellationToken).ConfigureAwait(false);
if (response.StatusCode is not (HttpStatusCode.Created or HttpStatusCode.OK))
{
// The body may contain an OperationOutcome that echoes request content, so it is not put in the message.
throw new HttpRequestException($"EHR refused the appointment with status {(int)response.StatusCode}.", null, response.StatusCode);
}
string id = response.Headers.Location?.ToString().Split("/Appointment/").Last().Split('/')[0] ?? await ReadIdAsync(response, cancellationToken).ConfigureAwait(false);
return new EhrOutcome(response.StatusCode == HttpStatusCode.Created, id);
}
public static JsonObject ToFhir(AppointmentEvent appointment, string identifierSystem) => new()
{
["resourceType"] = "Appointment",
["identifier"] = new JsonArray(new JsonObject { ["system"] = identifierSystem, ["value"] = appointment.AppointmentId }),
["status"] = "booked",
["slot"] = new JsonArray(new JsonObject { ["reference"] = $"Slot/{appointment.SlotId}" }),
["created"] = appointment.RecordedAt.ToString("yyyy-MM-ddTHH:mm:sszzz"),
["participant"] = new JsonArray(new JsonObject
{
["actor"] = new JsonObject { ["reference"] = appointment.PatientReference },
["status"] = "accepted",
}),
};
private static async Task<string> ReadIdAsync(HttpResponseMessage response, CancellationToken cancellationToken)
{
if (response.Content.Headers.ContentLength is 0) { return string.Empty; }
await using Stream body = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using JsonDocument document = await JsonDocument.ParseAsync(body, cancellationToken: cancellationToken).ConfigureAwait(false);
return document.RootElement.TryGetProperty("id", out JsonElement id) ? id.GetString() ?? string.Empty : string.Empty;
}
}The Appointment carries references to the slot and the patient and nothing else about the patient. The error path is deliberate too: a refused request raises an exception with the status code and without the response body, because an OperationOutcome can echo request content and exception messages end up in logs.
This is the generic R4 interaction. An EHR that exposes booking as an operation, as the Argonaut Scheduling guide describes, needs its own implementation of the same interface, and that is the point of the adapter boundary: the dispatcher and everything upstream of it do not change. Where an EHR offers no write interface at all, the adapter becomes an HL7 v2 scheduling message or a work queue for staff, and the outbox still holds the truth about what has and has not been communicated.
The last piece protects the platform from the EHR. When the EHR is failing, continuing to call it ties up workers and adds load to a system that is already in trouble.
namespace Booking.Core;
public enum CircuitState { Closed, Open, HalfOpen }
/// <summary>
/// Stops calling an EHR that is failing, so a vendor outage or maintenance window costs the platform a queue
/// of pending events and not its worker threads. After <paramref name="openFor"/> one trial call is let through.
/// </summary>
public sealed class CircuitBreaker(int failureThreshold, TimeSpan openFor, TimeProvider clock)
{
private readonly object _gate = new();
private int _consecutiveFailures;
private DateTimeOffset _openedAt;
private bool _open;
private bool _trialInFlight;
public CircuitState State
{
get
{
lock (_gate)
{
if (!_open) { return CircuitState.Closed; }
return clock.GetUtcNow() - _openedAt >= openFor ? CircuitState.HalfOpen : CircuitState.Open;
}
}
}
/// <summary>True if a call may be made now. In the half-open state only one caller is admitted.</summary>
public bool TryEnter()
{
lock (_gate)
{
if (!_open) { return true; }
if (clock.GetUtcNow() - _openedAt < openFor || _trialInFlight) { return false; }
_trialInFlight = true;
return true;
}
}
public void RecordSuccess()
{
lock (_gate)
{
_consecutiveFailures = 0;
_open = false;
_trialInFlight = false;
}
}
public void RecordFailure()
{
lock (_gate)
{
_trialInFlight = false;
if (_open || ++_consecutiveFailures >= failureThreshold)
{
_open = true;
_openedAt = clock.GetUtcNow();
}
}
}
}Between the commit and the delivery, the patient holds a confirmed appointment that the clinician cannot yet see. In normal running that interval is short. During an EHR outage it is as long as the outage. The age of the oldest undelivered event is therefore a safety measure and not only an operational one: it needs an alert, an owner, and a manual procedure for the clinic when it exceeds the agreed limit. Record this in the hazard log with the outbox alert as the mitigation.
Test results

| Case | Result |
|---|---|
| 200 simultaneous requests for one slot | One booked, 199 told the slot is taken, one outbox event |
| The same request retried with its idempotency key | The original booking returned, no second event |
| EHR fails twice, then answers | Both events stay in the outbox and are delivered on the next pass, once each |
| EHR stores the appointment and the acknowledgement is lost | Delivered a second time, recognised, still one appointment |
| EHR stays down with twelve bookings waiting | All twelve bookings accepted. Five calls made, then the circuit opens and seven are skipped |
| Cool-down passes, EHR still down | One trial call, which fails, and the circuit reopens |
| EHR returns | The backlog of twelve drains and the circuit closes |
| Audit entries | One for every delivery attempt, each carrying an appointment id and no patient reference |
Those run in memory. The FHIR interactions were also run against a real server, HAPI FHIR 8.0.0 in a container, from Python and through the C# gateway.
| Interaction | Expected by the specification | Observed on HAPI FHIR 8.0.0 |
|---|---|---|
Two concurrent PUT Slot with the same If-Match | One succeeds, one is refused | 200 and 409 |
A later PUT with the stale version | 412 Precondition Failed | 409 Conflict |
POST Appointment three times with the same If-None-Exist | 201, then 200 twice | 201, 200, 200 |
| Search by the business identifier afterwards | One Appointment | One Appointment |
| The C# gateway delivering one event twice | Created once, same id returned | Created once, same id returned |
The second row is the kind of detail that only appears when the code meets a server. The specification gives 412 for a version mismatch and allows 409 for other conflicts. This server answered 409 for both. A client that treats only 412 as “somebody else got there first” would report a server error to the patient. The version-aware update is also the mechanism the first ownership option depends on: if the EHR owns the slot and exposes it over FHIR, If-Match is what stops two writers both taking it.
Security design
The Security Rule’s technical safeguards are five standards. Some of their implementation specifications are required and some are addressable, which means they must be assessed and either implemented or replaced by a documented equivalent. The table maps each to an element of the design.
| 45 CFR 164.312 | Specification | In this design |
|---|---|---|
| (a) Access control | Unique user identification (required) | Every patient and staff member has their own identity in Entra. Services call each other with managed identities, so there are no shared accounts |
| Emergency access procedure (required) | A break-glass role with its own approval and alerting, exercised on a schedule | |
| Automatic logoff (addressable) | Short-lived access tokens and an idle timeout in the apps | |
| Encryption and decryption (addressable) | Encryption at rest on every store, with Always Encrypted for the most sensitive columns and keys in Key Vault | |
| (b) Audit controls | Record and examine activity | The append-only audit trail: actor, action, record identifier and time for every access and every EHR write |
| (c) Integrity | Authenticate ePHI (addressable) | FHIR resource versions and If-Match on updates; the outbox as the record of what was sent |
| (d) Person or entity authentication | Verify the claimed identity | OpenID Connect with MFA for people; managed identities and client assertions for systems |
| (e) Transmission security | Integrity controls and encryption (addressable) | TLS on every hop, including service to service and service to EHR |
Three practices matter as much as any control in that table, because they decide how much PHI there is to protect.
- Hold references, not records. The platform database stores a patient reference against each appointment. Demographics and clinical data are read from the EHR when a screen needs them. A national identifier such as a Social Security number has no place in a booking schema.
- Keep PHI out of the places nobody secures. Logs, traces, cache keys, queue message properties and URLs carry identifiers only. The sample’s audit entries and its gateway errors are written that way, and a test fails if a patient reference appears in the audit trail.
- Know which services are covered. Each cloud service that touches PHI has to be within the scope of the business associate agreement. That includes the video service used for telehealth and any SMS or email provider used for reminders, and it is a reason reminders should say that an appointment exists and little more.
Operations
The design gives operations a small number of signals that mean something.
| Signal | What it tells you | Response |
|---|---|---|
| Age of the oldest undelivered outbox event | How long the EHR has been behind the platform | Alert at a threshold agreed with the clinical safety officer; invoke the clinic’s manual procedure beyond it |
| Circuit state for each EHR | Whether that EHR is being called at all | Open for longer than a maintenance window is an incident with the vendor |
| Booking refusals by reason | Slot taken, unknown slot, or validation failure | A rise in “taken” suggests the displayed availability is stale |
| Conflict responses from the EHR | 409 and 412 on writes | Expected in small numbers; a trend means two writers disagree about ownership |
| Reconciliation differences | Platform bookings with no EHR appointment, and the reverse | A daily comparison, with every difference investigated |
Reconciliation is the control that catches whatever the design did not anticipate. Two systems that each hold part of the truth will drift, and a scheduled comparison of the allocation is what turns drift into a ticket. Recovery objectives belong here too: because the outbox is in the transactional database, restoring that database restores the list of what still has to be sent, and the conditional create makes it safe to send again.
Cost drivers
The bill for a platform like this is shaped by a handful of drivers, and each has a design lever.
| Cost driver | Scales with | Design lever |
|---|---|---|
| EHR API calls | Reads of availability and patient data | Cache read models with a short lifetime; never cache the booking decision |
| Compute | Concurrent sessions and dispatcher throughput | Scale services on HTTP load and the dispatcher on outbox depth |
| Database | Transaction rate and retention | Keep the platform schema small; the chart stays in the EHR |
| Messaging and notifications | Events and reminders per appointment | One event per state change; batch reminders |
| Log and audit retention | Volume and the retention period policy requires | Separate the audit trail from diagnostic logs, which can be kept for far less time |
| Vendor integration | Each EHR and each interface | The adapter boundary limits this to one component per vendor |
Risks and mitigations
| Risk | Severity | Mitigation |
|---|---|---|
| An EHR does not offer an appointment write interface, or offers it late | High | Confirm in the vendor sandbox before design sign-off; the adapter can fall back to HL7 v2 or a staff work queue |
| Double booking between portal and front desk | High | An explicit allocation of online-bookable slots, plus daily reconciliation |
| A confirmed booking is not visible in the EHR during an outage | High | Outbox age alert and a manual clinic procedure, recorded in the hazard log |
| PHI appears in logs or traces | High | Identifier-only logging as a coding standard, enforced by tests and by sampling production logs |
| Vendor rate limits throttle the dispatcher | Medium | Limits taken from each vendor’s agreement and configured per adapter, with the circuit breaker as the backstop |
| Identity platform change | Medium | Standard OpenID Connect only, so the identity provider can be replaced without touching the services |
Key takeaways
- Decide who owns each slot before anything else. The EHR, or an allocation released to the platform, are both defensible. A cached copy booked optimistically is not.
- Make the booking decision with a conditional update inside one database transaction, and write the outbox event in the same transaction.
- Delivery to the EHR is at least once, so make the write idempotent: a business identifier and a conditional create on FHIR, or the vendor’s equivalent.
- The certified EHR API is a read API. Treat an appointment write as a per-vendor dependency to be proven in a sandbox.
- Hold references and not records, keep PHI out of logs, and treat the age of the oldest undelivered event as a clinical safety measure.
If you have built the booking path against a commercial EHR and found its scheduling interface behaving differently from the specification, I would like to hear about it in the comments.
The booking core and its 20 checks run on .NET 8 in GitHub Actions. The FHIR interactions run in the same pipeline against HAPI FHIR 8.0.0 in a container: eight checks from Python 3.13, and three through the C# gateway. All data is synthetic. No Azure resource and no commercial EHR was involved, so the choice of Azure services and the statements about vendor interfaces rest on the documentation cited below and on the design reasoning set out above. The SQL transaction described in the ledger’s comments was not executed; the in-memory ledger stands in for it. The workflow run has the logs.
The complete sample is on GitHub: blog-samples-working-repo/patient-provider-platform. It contains the booking ledger, the outbox dispatcher, the circuit breaker, the FHIR gateway, the self-test, and the Python drill for the FHIR server.
Glossary
- EHR— Electronic health record system: here, the system of record for clinical data and the schedule.
- PHI— Protected health information under HIPAA; ePHI when held electronically.
- BAA— Business associate agreement: the contract HIPAA requires with any party that handles PHI on a covered entity’s behalf.
- Transactional outbox— Writing an event to the same database, in the same transaction, as the change it describes, for later delivery.
- Conditional create— A FHIR create that does nothing if a resource matching the given search already exists.
- Version-aware update— A FHIR update sent with If-Match, refused if the resource has changed since it was read.
- Circuit breaker— A guard that stops calls to a failing dependency for a period, then admits a trial call.
- Idempotency key— A client-generated identifier repeated on every retry of one request, so the server acts once.
References & Further Reading
- → 45 CFR 164.312, Technical safeguards— The five standards and their required and addressable specifications.
- → 170.315(g)(10) Standardized API for patient and population services— What the certified EHR API must do: respond to data and search requests.
- → FHIR R4 RESTful API— Conditional create with If-None-Exist and version-aware updates with If-Match.
- → Argonaut Scheduling Implementation Guide— Patient-based and provider-based scheduling scenarios and operations, on FHIR STU3.
- → Azure AD B2C frequently asked questions— End of sale to new customers from 1 May 2025 and the support commitment.
- → Transactional Outbox pattern, Azure Architecture Center— The pattern, duplicate detection and idempotent consumers.
- → Circuit Breaker pattern, Azure Architecture Center— Closed, open and half-open states.
- → Sample code for this article— Booking core in C#, FHIR drill in Python, and the CI workflow that runs them.
Related on this site: FHIR Integration Best Practices and Azure API Management for Healthcare.
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.