The Azure Cosmos DB Blog

All about Azure Cosmos DB and Azure

Using Azure Cosmos DB and Function Apps for updating Medical Devices from HL7 FHIR

star This is a sample chapter from a free eBook I am co-authoring with Cory G. Stevenson, Data Solution Architect & Data Scientist with Microsoft.
The eBook is based upon the HL7 FHIR on Azure Device Framework from the HL7 FHIR on Azure eBook available here Downlaod

Recently we were brought in to design and develop an IoT solution for an Medical Device manufacturer. Their devices are used through out the world.

Business Requirements

The Software Update Service is to be one of several Microservices that will comprise the complete IoT System. These services include Provisioning, Management, Logging, Analysis, Monitoring and Security

INFO: The chapter before this one, is about Configuring our Azure Cosmos DB Data Repository for HL7 FHIR Resources.

Functional Requirements

  • The service would support an Multi-Tenancy Architecture.
  • Ability to have the software updates as close as possible to their customers Medical Device System (MDS), Virtual Medical Device (VMD) or a Channel.
  • A Form-Post from a web application will be used to send the software update file, along with metadata to the Software Update Service.
  • All Device Data was to be stored as HL7 FHIR Resources.
  • All data must be encrypted at Rest and Intransit.

NOTE: There are three HL7 FHIR Medical Device Resources: Device, DeviceMetric, and DeviceComponent.

In FHIR, the “Device” is the “administrative” resource for the device (it does not change much and has manufacturer information etc.), whereas the DeviceComponent and DeviceMetric (which is really a kind of DeviceComponent) model the physical part, including operation status and is much more volatile.

The physical composition of a Device is done by the DeviceComponents pointing to their “parent” component using DeviceComponent.parent. All components point to the “logical” Device they belong to, using DeviceComponent.source.

HL7 FHIR has a REST API. The API is hosted in an Azure Web Application. It can be used by Practitioners and Healthcare EHR systems to query the Device Resources.


INFO: Device, DeviceMetric, DeviceComponent documents have been created from the Device was Provisioned.

We decided to create an Azure Microservice for the complete Software Update Service. This would provide support for multi-tenancy.

  • An Azure Function App would receive the software update from a Form-Data POST.
  • An Azure Durable Function would send the software update to the Medical Device System (MDS), Virtual Medical Device (VMD) or a Channel.
  • Azure Cosmos DB SQL API would be used as an HL7 FHIR Server.
  • Azure Cosmos DB would be used to store the software update file as an Document Attachment to the FHIR DeviceComponent Resource.
  • The Software Update files would be stored in Azure Content Delivery Network (CDN) using Azure Blob Storage. The files will be cached at physical nodes in the United States, Europe, Asia, Australia, and South America.
  • Our Cosmos DB Database Account will use Global Distribution to the regions in the United States, Europe, Asia, Australia, and South America.
  • All the Azure Services support data encryption both at Rest and Intransit.

INFO: The setup and configuration of the HL7 FHIR on Azure Cosmos DB, along with the HL7 FHIR Rest Api is outside the scope of the solution.


Posting Device Software Update to HL7 FHIR Server (Azure Cosmos DB)



  1. Web App does a Form-Data POST to Function App.
  2. Function App Inserts Software Update file in Azure Blob Storage.
  3. Function App updates HL7 FHIR DeviceComponent Resource (document).
  4. Function App returns Response to Web App.

FormData Function App

Source Code


using System;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using HttpMultipartParser;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.WindowsAzure.Storage;
using Attachment = Microsoft.Azure.Documents.Attachment;


namespace CosmosDBFormData
    public static class FormData
        private static readonly string Endpoint = ConfigurationManager.AppSettings["endpoint"];
        private static readonly string AuthKey = ConfigurationManager.AppSettings["authKey"];
        private static readonly string Database = ConfigurationManager.AppSettings["database"];
        private static readonly string Collection = ConfigurationManager.AppSettings["collection"];
        private static readonly string ConnectionString = ConfigurationManager.AppSettings["storageConnectionString"];
        private static readonly string BlobContainer = ConfigurationManager.AppSettings["blobContainer"];
        private static readonly string CdnUrl = ConfigurationManager.AppSettings["cdnUrl"];

        private static readonly DocumentClient Client = new DocumentClient(new Uri(Endpoint), AuthKey,
            new ConnectionPolicy
                ConnectionMode = ConnectionMode.Direct,
                ConnectionProtocol = Protocol.Tcp

        public static async Task<HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            HttpRequestMessage req, TraceWriter log)
            var storageAccount = CloudStorageAccount.Parse(ConnectionString);
            var cloudBlobClient = storageAccount.CreateCloudBlobClient();
            var cloudBlobContainer = cloudBlobClient.GetContainerReference(BlobContainer);
            var data = req.Content.ReadAsStreamAsync();
            var parser = new MultipartFormDataParser(data.Result);
            var deviceId = parser.GetParameterValue("DeviceId");
            var file = parser.Files.FirstOrDefault();
            if (file == null)
                return req.CreateErrorResponse(HttpStatusCode.BadRequest, "The Attachment File is missing");

            var fileName = file.FileName;
            var attachment = file.Data;
            var feedOptions = new FeedOptions {MaxItemCount = 1};

                // Get the DeviceComponent document
                var doc = Client.CreateDocumentQuery(UriFactory.CreateDocumentCollectionUri(Database, Collection),
                    $"SELECT * FROM d WHERE d.resourceType = \'DeviceComponent\' AND d.source.reference = \' Device/\'{deviceId}", feedOptions);

                Document d = doc.FirstOrDefault();

                    var cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);

                        await cloudBlockBlob.UploadFromStreamAsync(attachment);
                    catch (StorageException ex)
                        return req.CreateErrorResponse(HttpStatusCode.NotFound, ex.Message);
                        await Client.CreateAttachmentAsync(d.Id, new Attachment
                            Id = fileName,
                            ContentType = file.ContentType,
                            MediaLink = $"{CdnUrl}/{fileName}"
                            var update = await Client.UpsertDocumentAsync(UriFactory.CreateDocumentCollectionUri(Database, Collection), d);

                            return req.CreateResponse(HttpStatusCode.OK,update.Resource.Id);
                        catch (DocumentClientException ex)
                            var statusCode = ex.StatusCode;
                            return req.CreateErrorResponse((HttpStatusCode) statusCode, ex.Message);
                    catch (DocumentClientException ex)
                        var statusCode = ex.StatusCode;
                        return req.CreateErrorResponse((HttpStatusCode) statusCode, ex.Message);
                catch (DocumentClientException ex)
                    var statusCode = ex.StatusCode;
                    return req.CreateErrorResponse((HttpStatusCode) statusCode, ex.Message);
            catch (DocumentClientException ex)
                var statusCode = ex.StatusCode;
                return req.CreateErrorResponse((HttpStatusCode) statusCode, ex.Message);

HL7 FHIR Resources for Medical Devices

Device Resource Document Template

  "resourceType" : "Device",
  // from Resource: id, meta, implicitRules, and language
  // from DomainResource: text, contained, extension, and modifierExtension
  "identifier" : [{ Identifier }], // Instance identifier
  "udi" : { // Unique Device Identifier (UDI) Barcode string
    "deviceIdentifier" : "<string>", // Mandatory fixed portion of UDI
    "name" : "<string>", // Device Name as appears on UDI label
    "jurisdiction" : "<uri>", // Regional UDI authority
    "carrierHRF" : "<string>", // UDI Human Readable Barcode String
    "carrierAIDC" : "<base64Binary>", // UDI Machine Readable Barcode String
    "issuer" : "<uri>", // UDI Issuing Organization
    "entryType" : "<code>" // barcode | rfid | manual +
  "status" : "<code>", // active | inactive | entered-in-error | unknown
  "type" : { CodeableConcept }, // What kind of device this is
  "lotNumber" : "<string>", // Lot number of manufacture
  "manufacturer" : "<string>", // Name of device manufacturer
  "manufactureDate" : "<dateTime>", // Date when the device was made
  "expirationDate" : "<dateTime>", // Date and time of expiry of this device (if applicable)
  "model" : "<string>", // Model id assigned by the manufacturer
  "version" : "<string>", // Version number (i.e. software)
  "patient" : { Reference(Patient) }, // Patient to whom Device is affixed
  "owner" : { Reference(Organization) }, // Organization responsible for device
  "contact" : [{ ContactPoint }], // Details for human/organization for support
  "location" : { Reference(Location) }, // Where the resource is found
  "url" : "<uri>", // Network address to contact device
  "note" : [{ Annotation }], // Device notes and comments
  "safety" : [{ CodeableConcept }] // Safety Characteristics of Device

Device Component Document Template

  "resourceType" : "DeviceComponent",
  // from Resource: id, meta, implicitRules, and language
  // from DomainResource: text, contained, extension, and modifierExtension
  "identifier" : { Identifier }, // R!  Instance id assigned by the software stack
  "type" : { CodeableConcept }, // R!  What kind of component it is
  "lastSystemChange" : "<instant>", // Recent system change timestamp
  "source" : { Reference(Device) }, // Top-level device resource link
  "parent" : { Reference(DeviceComponent) }, // Parent resource link
  "operationalStatus" : [{ CodeableConcept }], // Current operational status of the component, for example On, Off or Standby
  "parameterGroup" : { CodeableConcept }, // Current supported parameter group
  "measurementPrinciple" : "<code>", // other | chemical | electrical | impedance | nuclear | optical | thermal | biological | mechanical | acoustical | manual+
  "productionSpecification" : [{ // Specification details such as Component Revisions, or Serial Numbers
    "specType" : { CodeableConcept }, // Type or kind of production specification, for example serial number or software revision
    "componentId" : { Identifier }, // Internal component unique identification
    "productionSpec" : "<string>" // A printable string defining the component
  "languageCode" : { CodeableConcept } // Language code for the human-readable text strings produced by the device

Device Metric Document Template

  "resourceType" : "DeviceMetric",
  // from Resource: id, meta, implicitRules, and language
  // from DomainResource: text, contained, extension, and modifierExtension
  "identifier" : { Identifier }, // R!  Unique identifier of this DeviceMetric
  "type" : { CodeableConcept }, // R!  Identity of metric, for example Heart Rate or PEEP Setting
  "unit" : { CodeableConcept }, // Unit of Measure for the Metric
  "source" : { Reference(Device) }, // Describes the link to the source Device
  "parent" : { Reference(DeviceComponent) }, // Describes the link to the parent DeviceComponent
  "operationalStatus" : "<code>", // on | off | standby | entered-in-error
  "color" : "<code>", // black | red | green | yellow | blue | magenta | cyan | white
  "category" : "<code>", // R!  measurement | setting | calculation | unspecified
  "measurementPeriod" : { Timing }, // Describes the measurement repetition time
  "calibration" : [{ // Describes the calibrations that have been performed or that are required to be performed
    "type" : "<code>", // unspecified | offset | gain | two-point
    "state" : "<code>", // not-calibrated | calibration-required | calibrated | unspecified
    "time" : "<instant>" // Describes the time last calibration has been performed


  • You have seen how easy it is to use an Azure Function App to receive a Form-Post.
  • You have learned how to save the Software Update file to CDN as an Cosmos DB Document Attachment.

Next Step

  • You will see how we used Azure Durable Functions to publish the Software Updates to the Azure IoT Hubs.

Azure Best Practices

Recently a client (IoT Device Manufacturer) asked me to provide them with a Best Practices guideline for migrating their IoT Services to Azure. I told them that there wasn’t a single guideline that encompasses everything, that there are many Best Practices Guidelines available.

I recommended that they start off with selecting the Architecture that is best suited to meet business requirements.

This is what I provided them.

Application Architecture Guide

1. We start off with selecting the Architectural Style.

There are several Architectural Styles that can be used. It has been my experience that the Microservices Architectural Style works best for IoT solutions. Another is the Event-driven Architectural Style.

2. Decide on the technology that will be used for Azure Applications.

  • Compute Options – refers to the hosting model for the computing resources that your application runs on. The main compute options available are Virtual Machines, App Service, Service Fabric, Azure Container Services, Azure Functions, Azure Batch, and Cloud Services.
  • Data Store – a single data store is usually not the best approach. Instead, it’s often better to store different types of data in different data stores, each focused towards a specific workload or usage pattern. These stores include Key/value stores, Document databases, Graph databases, Column-family databases, Data Analytics, Search Engine databases, Time Series databases, Object storage, and Shared files.

3. Following Design Principles is next

  • In a distributed system, failures happen. Design your application to be self healing when failures occur.
  • Build redundancy into your application, to avoid having single points of failure.
  • Minimize coordination between application services to achieve scalability.
  • Design your application so that it can scale horizontally, adding or removing new instances as demand requires.
  • Use partitioning to work around database, network, and compute limits.
  • Design your application so that the operations team has the tools they need.
  • When possible, use platform as a service (PaaS) rather than infrastructure as a service (IaaS).
  • Pick the storage technology that is the best fit for your data and how it will be used.
  • All successful applications change over time. An evolutionary design is key for continuous innovation.
  • Every design decision must be justified by a business requirement.

Software Quality is extremely important for a successful cloud application.

  • Scalability – The ability of a system to handle increased load.
  • Availability – The proportion of time that a system is functional and working.
  • Resiliency – The ability of a system to recover from failures and continue to function.
  • Management Operations processes that keep a system running in production.
  • Security – Protecting applications and data from threats.

Enforcing the use of Cloud Design Patterns will insure that your applications will be reliable, scalable, and secure.


  • Providing a high-level summary for choosing their Architectural Style and the Compute/ Data Store Technology choices, made it easier for them to understand.
  • Once they reviewed the information, I was able to answer their questons and provide them guidance on implementing Steps 1 and 2.
« Older posts
%d bloggers like this:
Skip to toolbar