Reference Architecture: A Patient-Provider Platform over Two EHRs on Azure

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.

⚖️
COMPLIANCE

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.

ConstraintConsequence for the design
The EHRs stay the systems of record for clinical data and for the scheduleThe platform stores references and its own transactional state. It does not become a third copy of the chart
Two EHRs with different integration interfacesVendor differences are confined to adapters behind one internal contract
The certified EHR API is a read APIReading 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 elsePatient-facing functions must not depend on a synchronous call to the EHR succeeding
Front-desk staff book into the same schedule from inside the EHRSomebody has to own each slot. This is the decision the next section turns on
HIPAA Security RuleUnique 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

Reference architecture. A patient app signs in with Entra External ID and calls API Management, which forwards to a booking service. The service marks the slot busy and writes the appointment and an outbox event in one transaction in the platform database. An outbox dispatcher with a circuit breaker delivers events through EHR adapters to two EHRs. An append-only audit trail records identifiers only.
The platform at container level. The booking decision is made in one transaction in the platform database and reaches the EHR afterwards.
%%{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
ElementAzure serviceWhy
Patient identityMicrosoft Entra External IDCustomer 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 doorAzure API ManagementToken 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
ServicesAzure Container Apps or AKSStateless .NET services scaled on HTTP load, with the dispatcher scaled on queue depth
Transactional storeAzure SQL DatabaseSlots, appointments and the outbox need one ACID transaction. Sensitive columns can use Always Encrypted
MessagingAzure Service BusCarries events to notifications and other consumers, with duplicate detection on the event id
Secrets and keysAzure Key Vault with managed identitiesNo connection strings or EHR client secrets in configuration
MonitoringAzure Monitor and Microsoft Defender for CloudMetrics 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.

OptionHow it worksStrengthWeakness
The EHR owns every slotThe portal calls the EHR’s booking interface synchronously and shows the patient the answerOne authority, so no double booking between portal and front deskBooking is down whenever the EHR is, and depends on the vendor offering a booking interface with concurrency control
The platform owns an allocationThe EHR releases a block of slots for online booking. The platform decides who gets each one and reports the result to the EHRBooking keeps working through an EHR outage, and the platform controls concurrencyTwo systems of record for a short time. Needs reconciliation and an agreed rule for the allocation
The platform keeps a copy and hopesSlots are cached from the EHR and booked optimistically, with the EHR write as a later stepSimple to buildDouble 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.

C#84 lines
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 delivered
C#51 lines
namespace 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.

C#59 lines
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.

C#63 lines
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();
            }
        }
    }
}
⚠️
CLINICAL SAFETY

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

Four test results. One of 200 simultaneous requests for a slot is booked. One appointment exists after a lost acknowledgement caused a second delivery. Twelve of twelve bookings were accepted while the EHR was down, with five calls made before the circuit opened. The FHIR server returned 409 for a stale If-Match where the specification says 412.
Four failure cases from the sample’s test run.
CaseResult
200 simultaneous requests for one slotOne booked, 199 told the slot is taken, one outbox event
The same request retried with its idempotency keyThe original booking returned, no second event
EHR fails twice, then answersBoth events stay in the outbox and are delivered on the next pass, once each
EHR stores the appointment and the acknowledgement is lostDelivered a second time, recognised, still one appointment
EHR stays down with twelve bookings waitingAll twelve bookings accepted. Five calls made, then the circuit opens and seven are skipped
Cool-down passes, EHR still downOne trial call, which fails, and the circuit reopens
EHR returnsThe backlog of twelve drains and the circuit closes
Audit entriesOne 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.

InteractionExpected by the specificationObserved on HAPI FHIR 8.0.0
Two concurrent PUT Slot with the same If-MatchOne succeeds, one is refused200 and 409
A later PUT with the stale version412 Precondition Failed409 Conflict
POST Appointment three times with the same If-None-Exist201, then 200 twice201, 200, 200
Search by the business identifier afterwardsOne AppointmentOne Appointment
The C# gateway delivering one event twiceCreated once, same id returnedCreated 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.312SpecificationIn this design
(a) Access controlUnique 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 controlsRecord and examine activityThe append-only audit trail: actor, action, record identifier and time for every access and every EHR write
(c) IntegrityAuthenticate ePHI (addressable)FHIR resource versions and If-Match on updates; the outbox as the record of what was sent
(d) Person or entity authenticationVerify the claimed identityOpenID Connect with MFA for people; managed identities and client assertions for systems
(e) Transmission securityIntegrity 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.

SignalWhat it tells youResponse
Age of the oldest undelivered outbox eventHow long the EHR has been behind the platformAlert at a threshold agreed with the clinical safety officer; invoke the clinic’s manual procedure beyond it
Circuit state for each EHRWhether that EHR is being called at allOpen for longer than a maintenance window is an incident with the vendor
Booking refusals by reasonSlot taken, unknown slot, or validation failureA rise in “taken” suggests the displayed availability is stale
Conflict responses from the EHR409 and 412 on writesExpected in small numbers; a trend means two writers disagree about ownership
Reconciliation differencesPlatform bookings with no EHR appointment, and the reverseA 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 driverScales withDesign lever
EHR API callsReads of availability and patient dataCache read models with a short lifetime; never cache the booking decision
ComputeConcurrent sessions and dispatcher throughputScale services on HTTP load and the dispatcher on outbox depth
DatabaseTransaction rate and retentionKeep the platform schema small; the chart stays in the EHR
Messaging and notificationsEvents and reminders per appointmentOne event per state change; batch reminders
Log and audit retentionVolume and the retention period policy requiresSeparate the audit trail from diagnostic logs, which can be kept for far less time
Vendor integrationEach EHR and each interfaceThe adapter boundary limits this to one component per vendor

Risks and mitigations

RiskSeverityMitigation
An EHR does not offer an appointment write interface, or offers it lateHighConfirm 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 deskHighAn explicit allocation of online-bookable slots, plus daily reconciliation
A confirmed booking is not visible in the EHR during an outageHighOutbox age alert and a manual clinic procedure, recorded in the hazard log
PHI appears in logs or tracesHighIdentifier-only logging as a coding standard, enforced by tests and by sampling production logs
Vendor rate limits throttle the dispatcherMediumLimits taken from each vendor’s agreement and configured per adapter, with the circuit breaker as the backstop
Identity platform changeMediumStandard 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.

ℹ️
HOW THIS WAS CHECKED

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.

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

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.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.