R-TF-012-029 Software Architecture Description
Introduction
Purpose
This document describes the software architecture for the medical device software, including the high-level structure, key software components, interfaces, and design decisions. The architecture provides the framework for implementing the software requirements specified in the Software Requirements Specification (SRS).
Scope
This architecture description covers:
- High-level software architecture and system decomposition
- Software elements and their responsibilities
- Interfaces between software elements and external systems
- SOUP (Software of Unknown Provenance) components
- Data flow and control flow
- Architectural decisions and rationale
Architectural Overview
What is this for?
The device offers a workflow to perform an analysis of images presenting skin conditions as specified in the Intended Use.
The workflow offered by the device to the integrators consists of the following main steps:
- The user decides whether to perform a diagnosis support or severity assessment.
- Diagnosis Support: The user uploads up to 3 images of the skin condition for analysis.
- Severity Assessment: The user collects required subjective information from the patient (e.g., itch intensity, sleep disturbance) and uploads 1 image of the skin condition for analysis.
- The device analyzes the provided information by calling the experts associated to the involved AI models and returns the results to the user.
Diagnosis support
This endpoint allows the user to upload up to 3 images of a skin condition for analysis. The device validates the images for quality and domain relevance before calling the expert associated with the Diagnosis Support AI model. The expert processes the images and returns a respose contanining:
- An aggregated ICD probability distribution from the set of images as the software requirement (SRS-Q3Q).
- A per-image ICD diagnosis with their corresponding explainability heat maps (SRS-0AB).
- The model sensitivity and specificity metrics (SRS-1XR).
- The entropy score for allowing the user to assess the uncertainty of the AI model's predictions (SRS-58W).
- The following clinical indicators:
- High priority referral (SRS-71I)
- The indicator of malignancy in the report (SRS-8HY)
- The indicator of the image presenting a pigmented lesion (SRS-D08)
- The indicator of the presence of a condition (SRS-JLM)
- The indicator of needing an urgent referral (SRS-KAS)
Severity assessment
The severity assessment workflow involves the user collecting subjective information from the patient (e.g., itch intensity, sleep disturbance) and uploading 1 image of the skin condition. The device validates the image for quality and domain relevance before calling the requested experts that are associated with the Severity Assessment AI models. The expert processes the information and returns a response containing.
The severity assessment allows to calculate the following clinical signs:
- Binary classification outputs for presence/absence detection of clinically significant features:
- Wound characteristics: perilesional erythema, wound edge morphology (damaged, delimited, diffuse, thickened, indistinguishable), perilesional maceration, exudate types (fibrinous, purulent, bloody, serous), biofilm-compatible tissue, affected tissue depth (intact skin, dermis-epidermis, subcutaneous, muscle, bone), wound bed tissue composition (necrotic, closed, granulation, epithelial, slough).
- Segmentation-based quantitative outputs for two-dimensional surface area measurements:
- Percentage coverage: relative area of detected features normalized to total lesion or anatomical region (e.g., erythema percentage, granulation tissue percentage, wound closure percentage, hair loss percentage, nail lesion percentage, pigmentary alteration percentage).
- Absolute measurements (when calibration available): surface area in cm², perimeter in cm, maximum length and width dimensions.
- Segmentation masks: pixel-level delineation with class labels (e.g., background, lesion, healthy tissue) enabling spatial analysis and longitudinal tracking.
- Applicable segmentation targets include: wound bed area, erythema extent, granulation tissue, biofilm/slough, necrosis, maceration, orthopedic material exposure, bone/cartilage/tendon exposure, hair loss, nail lesions, hypopigmentation/depigmentation, hyperpigmentation.
- Object detection and counting outputs for discrete lesion enumeration:
- Absolute counts: number of detected lesions or structures (e.g., inflammatory nodules, abscesses, draining/non-draining tunnels, papules, pustules, cysts, comedones, nodules, hives, hair follicles).
- Bounding box annotations: spatial coordinates for each detected object with class labels and confidence scores.
- Density metrics: lesions per unit area when combined with surface area quantification.
- Multi-class classification outputs for lesion staging and phenotyping:
- Wound stage classification (Stage 0, I, II, III, IV) according to standardized protocols.
- Hurley staging (I, II, III) for hidradenitis suppurativa severity.
- Inflammatory activity status (active vs. quiescent disease).
- Acne severity grading (IGA scale 0-4: Clear, Almost Clear, Mild, Moderate, Severe).
- Phenotype identification (e.g., follicular, inflammatory, mixed patterns).
Main functions
The software implements the following main functions and requirements:
- Generate an interpretative probability distribution of possible ICD categories by analysing images.
- Quantitative assessment of dermatological visual sign intensity.
- Quantitative assessment of dermatological structural features and lesion morphometry.
- Assess image adequacy on ingestion.
- Expose the device's functionality through a versioned, network-accessible API.
Main interfaces
RESTful API
Overview
The API Gateway exposes endpoints organized into the following categories:
- Authentication - User login and token management
- Clinical - Medical diagnosis and severity assessment
- Device - Device information and health checks
- Internal - System monitoring (not included in public API schema)
Authentication
POST /auth/login
Authenticate a user with username and password (OAuth2 Password Grant).
Request
Headers:
| Header | Required | Description |
|---|---|---|
Content-Type | Yes | application/json |
Body parameters:
{
"username": "string", // Required, min length: 1
"password": "string" // Required, min length: 1
}
Response
Status: 200 OK
{
"access_token": "string", // JWT access token
"token_type": "bearer", // Token type (default: "bearer")
"expires_in": 3600 // Token expiration time in seconds
}
Error Responses:
| Status | Description |
|---|---|
401 Unauthorized | Invalid username or password |
403 Forbidden | Account is locked |
Clinical
⚠️ All clinical endpoints require authentication
POST /clinical/diagnosis-support
Provide one or more base64-encoded images of the suspected lesion from different perspectives and receive a report with possible diagnoses.
Request
Headers:
| Header | Required | Description |
|---|---|---|
Authorization | Yes | Bearer <access_token> |
Content-Type | Yes | application/json |
Body parameters:
{
"images": ["base64_encoded_image_string"], // Required, 1-5 images
"extra_parameters": {
// Optional
"common": {
// Common parameters for all experts
"key": "value"
},
"expert_specific": {
// Parameters per expert
"expert_name": {
"key": "value"
}
}
}
}
Response
Status: 200 OK
{
"study_aggregate": {
"findings": {
"hypotheses": [
{
"identifier": "string", // e.g., "psoriasis"
"concepts": [
{
"name": "string", // e.g., "Psoriasis"
"code": "string", // e.g., SNOMED CT ID "44054006"
"terminology_system": "string" // e.g., "SNOMED CT"
}
],
"probability": 0.85, // 0-1 probability
"explanation": {
"attention_map": "base64_image" // Saliency heatmap (optional)
}
}
],
"risk_metrics": {
"any_condition_probability": 0.95,
"malignant_condition_probability": 0.02,
"pigmented_condition_probability": 0.15,
"urgent_referral_probability": 0.03,
"high_priority_referral_probability": 0.08
}
}
},
"image_analyses": [
{
"findings": {
"hypotheses": [...],
"risk_metrics": {...}
}
}
]
}
Error Responses:
| Status | Description |
|---|---|
401 Unauthorized | Missing or invalid authentication token |
403 Forbidden | User account is not active |
503 Service Unavailable | Control Plane unavailable |
POST /clinical/severity-assessment
Provide a base64-encoded image of the suspected lesion and the list of experts to consult, and receive a report with the severity assessment of visual signs.
Request
Headers
| Header | Required | Description |
|---|---|---|
Authorization | Yes | Bearer <access_token> |
Content-Type | Yes | application/json |
Body parameters:
{
"image": "base64_encoded_image_string", // Required
"experts": ["expert_identifier"], // Required, min 1 expert
"extra_parameters": {
// Optional
"common": {
"key": "value"
},
"expert_specific": {
"expert_name": {
"key": "value"
}
}
}
}
Response
Status: 200 OK
{
"image_analysis": {
"findings": [
{
"sign_identifier": "erythema",
"overall_severity_summary": "moderate erythema",
"overall_severity_score": 0.6,
"intensity": {
"grade": 2.5,
"grading_scale": "Legit.Health",
"confidence": 0.92
},
"extent": {
"regions": [
{
"mask": "base64_image",
"threshold": 0.5,
"confidence_map": "base64_image"
}
],
"annotated_image": "base64_image"
},
"count": {
"total": 5,
"detections": [
{
"identifier": "papule",
"bounding_box": {
"x": 100,
"y": 150,
"width": 50,
"height": 40
},
"confidence": 0.88
}
],
"annotated_image": "base64_image"
}
}
]
}
}
Error Responses:
| Status | Description |
|---|---|
401 Unauthorized | Missing or invalid authentication token |
403 Forbidden | User account is not active |
503 Service Unavailable | Control Plane unavailable |
Device
⚠️ All device endpoints require authentication
GET /device/about
Get device information including legal details and manufacturer information.
Request
Headers:
| Header | Required | Description |
|---|---|---|
Authorization | Yes | Bearer <access_token> |
Body parameters: None
Response
Status: 200 OK
{
"device_name": "string",
"description": "string",
"version": "2.3.1.0",
"release_date": "2024-01-15",
"manufacturer": {
"name": "string",
"description": "string",
"country_code": "ES",
"website": "https://example.com"
},
"udi": "string",
"alternate_identifiers": [
{
"system": "GMDN",
"code": "47905",
"issuing_authority": "GMDN Agency",
"description": "string"
}
],
"standards": [
{
"standard_name": "ISO 14971",
"standard_version": "2019"
}
],
"regulatory_clearances": [
{
"regulation": "EU MDR 2017/745",
"risk_class": "Class IIa",
"notified_body": "string",
"authorization_id": "string",
"authorization_date": "2024-01-01"
}
],
"claims": [
{
"description": "string",
"reference": "string"
}
],
"contact_email": "support@example.com",
"instructions_url": "https://example.com/ifu"
}
Error Responses:
| Status | Description |
|---|---|
401 Unauthorized | Missing or invalid authentication token |
403 Forbidden | User account is not active |
503 Service Unavailable | Control Plane unavailable |
GET /device/health
Check whether the device is operational.
Request Headers:
| Header | Required | Description |
|---|---|---|
Authorization | Yes | Bearer <access_token> |
Body parameters: None
Response
Status: 200 OK
The response schema is determined by the GetDeviceHealthUseCase implementation.
Error Responses:
| Status | Description |
|---|---|
401 Unauthorized | Missing or invalid authentication token |
403 Forbidden | User account is not active |
503 Service Unavailable | Control Plane unavailable |
Global system views
Architecture diagram
The following diagram illustrates the high-level software architecture of the medical device deployed in an AWS environment:
Connections
The medical device exposes a RESTful API over HTTPS for integrators to interact with its functionalities. This API is a kind of interface for allowing external systems to communicate with the sofware items known as "experts" that implement the different AI models.
Dataflow
The following diagram illustrates the high-level data flow within the medical device software architecture:
The following sequence diagram illustrates the interactions between the main software items during a typical user request:
Updatability / Patchability
The device update process is the following:
- The development team creates a new software version using the four-digit scheme (W.X.Y.Z) defined in GP-012. Digit X is incremented for major releases or significant feature additions (digit W is reserved for exceptional, fundamental changes), digit Y for minor feature improvements, and digit Z for bug fixes and patches.
- The new software version is deployed to the production environment after passing all required verification and validation activities.
- The API version follows an independent scheme (vA.B) decoupled from the software version. API major/minor increments reflect contract changes, and compatibility is documented in the API gateway to keep clients aligned with supported versions.
Security Use Cases
Controlled acccess to the API
Integrators access the medical device API using secure, credential-based authentication. Each integrator is assigned unique username and password pairs, which they use to log in via the API's authentication endpoint. Upon successful login, the API issues a signed JWT (JSON Web Token) that grants temporary access to clinical endpoints. This token is valid for a limited period; once it expires, the integrator must re-authenticate to obtain a new JWT and continue accessing the API. This mechanism ensures that only authorized users can interact with the medical device API, and that access is regularly validated.
Controlled access to user database
Access to the DynamoDB table containing user records is protected through AWS IAM (Identity and Access Management) and strict service-level authorization. The API service does not use long-lived credentials; instead, it assumes a dedicated IAM role that grants the minimum permissions required to interact with the DynamoDB table. AWS issues temporary, automatically rotated credentials to the API each time the role is assumed, ensuring that database access is both short-lived and tightly scoped.
Only the API can access the DynamoDB table. External systems, integrators, and users have no direct connection to DynamoDB; all operations must pass through the API’s authenticated and audited endpoints. Every request made by the API to DynamoDB is cryptographically signed using AWS Signature Version 4, guaranteeing request integrity and preventing unauthorized calls. This mechanism ensures that user data is only accessible through authorized backend components, that privileges are minimized, and that access is continuously validated via AWS security controls.
Controlled access to audit records database
Audit records are stored in a dedicated DynamoDB table that is protected through AWS IAM and a strict separation of privileges. The API service is granted access to audit storage using a specialized IAM role that provides write-only permissions. When the API needs to record an event, it temporarily assumes this audit-writer role, and AWS issues short-lived credentials that allow the service to store audit entries securely.
Each audit write operation must be executed through the API itself, since no external system or integrator has direct access to the audit table. All writes to DynamoDB are signed using AWS Signature Version 4, ensuring the authenticity and integrity of every audit record. The API cannot modify or delete existing audit entries, which guarantees immutability and preserves a reliable chronological trail of system activity. This mechanism ensures that audit data remains tamper-resistant, access is tightly controlled, and all operations involving audit logs are authenticated and traceable.
Logical architecture overview
Medical device software system
The medical device software system is composed of the following main software elements:
- API interface, which exposes the device's functionalities to integrators through a RESTful API.
- Control plane, which orchestrates the device's internal operations, manages requests, and coordinates interactions with the experts.
- Medical report builder for transforming dermatology-expert analysis results into canonical reports.
- Medical report exporter for exporting generated medical reports in standard formats like JSON.
- Experts, which are individual software items that implement specific AI models for diagnosis support, severity assessment and other non clinical functionalities.
The following diagram illustrates the high-level decomposition of the medical device software system and their relationships:
API Interface
The API Interface software item provides an HTTP-based entry point that allows integrator applications to access the medical device's clinical services. It exposes RESTful endpoints for authentication, diagnosis support, severity assessment, and device information retrieval. All requests and responses use JSON format, and protected endpoints require JWT-based authentication. The API Interface delegates clinical processing to the Control Plane and records all API calls for audit purposes.
The API Interface is composed of the following software units:
-
HTTP Routes: FastAPI router modules (
auth,clinical,device,internal) that define endpoint handlers for authentication (/auth/login), clinical analysis (/clinical/diagnosis-support,/clinical/severity-assessment), device information (/device/about,/device/health), and internal status monitoring (/internal/status). -
Authentication Dependencies: Middleware components that extract and validate JWT bearer tokens from incoming requests and verify that the authenticated user is active in the system.
-
Use Cases: Application layer components (
LoginUseCase,DiagnosisUseCase,SeverityAssessmentUseCase,GetDeviceLegalInfoUseCase,GetDeviceHealthUseCase,GetDeviceStatusUseCase,RecordCallUseCase) that orchestrate business operations by coordinating domain services and outbound adapters. -
Domain Services: The
AccountSecurityServiceimplements account lockout policies, managing failed login attempts and determining when to lock accounts based on configurable thresholds. -
Outbound Adapters: Implementations of port interfaces including:
HTTPControlPlaneClient: HTTP client adapter that communicates with the Control Plane for clinical analysis requests and device information.DynamoDBUserRepository,DynamoDBLockoutRepository,DynamoDBCallRecordRepository: Persistence adapters for user accounts, lockout records, and API call audit logs.Argon2AuthenticationService: Password hashing and verification using the Argon2 algorithm.JwtTokenService: JWT generation and validation for access tokens.
-
Call Recording Middleware: A Starlette middleware (
CallRecorderMiddleware) that intercepts all API requests and responses, capturing metadata (timing, authentication context, HTTP details, client information) and asynchronously persisting audit records. -
Dependency Injection Container: A Dependency Injector container (
Container) that wires together all services, repositories, use cases, and configuration, ensuring proper initialization and dependency management.
SOUPs
The API Interface leverages the following SOUP items:
- FastAPI: Web framework for building the HTTP API with automatic validation and OpenAPI documentation.
- Uvicorn: ASGI server for running the FastAPI application.
- Authlib: JWT encoding and decoding for access token generation and validation.
- Argon2-cffi: Secure password hashing using the Argon2 algorithm.
- HTTPX: Asynchronous HTTP client for communication with the Control Plane.
- aioboto3: Asynchronous AWS SDK client for DynamoDB operations.
- Pydantic: Data validation and settings management for request/response models and configuration.
- Dependency Injector: Dependency injection framework for wiring application components.
Interfaces with other software items
The API Interface interacts with the following software items and external systems:
- Control Plane: Receives delegated requests for diagnosis support, severity assessment, and device information via HTTP calls. The Control Plane orchestrates downstream processing through expert modules and report generation.
- Users Database (DynamoDB): Stores user account information including credentials and organization membership.
- Lockouts Database (DynamoDB): Maintains account lockout state for security enforcement.
- API Calls Database (DynamoDB): Persists audit records of all API calls for traceability and compliance.
- Integrator Application: External client applications that consume the API endpoints using JSON over HTTP with JWT bearer authentication.
The following figure depicts the API Interface architecture and its relations with other software items.
Control Plane
The Control Plane is the orchestration layer of the medical device backend. It receives requests from the API interface and coordinates the internal workflow needed to produce a clinical report. Its primary responsibility is to route user input through the appropriate expert services and report-building pipeline, returning a fully structured canonical report to the caller.
The Control Plane software item comprises the following software units:
-
REST HTTP Controller: Exposes HTTP endpoints for clinical workflows. The controller receives incoming requests from the API interface, validates input using Pydantic data models from the shared interface models library, and delegates processing to the appropriate use case. It also provides health check endpoints that verify connectivity to downstream services.
-
Diagnosis Workflow Use Case: Orchestrates the complete diagnosis workflow. It receives user diagnosis input, forwards it to the Expert Orchestrator to obtain expert analysis results, and then sends those results to the Report Builder to generate the final canonical diagnosis report.
-
Severity Workflow Use Case: Orchestrates the complete severity assessment workflow. It follows the same pattern as the diagnosis workflow, coordinating between the Expert Orchestrator and Report Builder to produce a canonical severity report.
-
Expert Orchestrator Gateway: An outgoing adapter that communicates with the Expert Orchestrator microservice via HTTP. This gateway abstracts the details of the HTTP transport and provides a domain-oriented interface for invoking expert analysis on user input.
-
Report Builder Gateway: An outgoing adapter that communicates with the Report Builder microservice via HTTP. This gateway abstracts the HTTP communication required to transform expert results into canonical report structures.
-
HTTP Client: A shared infrastructure component that manages persistent HTTP connections with retry logic and exponential backoff. It is used by the outgoing gateways to perform HTTP requests to downstream services.
-
Dependency Injection Container: Manages the lifecycle of all application components using the dependency-injector library. It wires configuration, gateways, use cases, and infrastructure components, ensuring proper initialization and shutdown of resources.
-
Settings Configuration: Loads application settings from environment variables using pydantic-settings. This includes service metadata, server configuration, downstream service URLs, and HTTP client parameters.
SOUPs
The Control Plane directly uses the following SOUP items:
- FastAPI: A modern Python web framework used to implement the REST API endpoints.
- Uvicorn: An ASGI server used to run the FastAPI application.
- Pydantic and pydantic-settings: Used for data validation, serialization, and configuration management.
- dependency-injector: A dependency injection framework used to manage component wiring and lifecycle.
- httpx: An asynchronous HTTP client library used for communication with downstream microservices.
- legithp-interface-models: A shared internal library that provides canonical data models for user input, expert results, and reports.
Interfaces with other software items
The Control Plane interfaces with the following software items:
- API Interface: The Control Plane receives HTTP requests from the API interface at the
/clinical-workflows/diagnosisand/clinical-workflows/severityendpoints. - Expert Orchestrator: The Control Plane invokes the Expert Orchestrator via HTTP to process user input and obtain clinical analysis results from expert AI/ML models.
- Report Builder: The Control Plane sends expert results to the Report Builder via HTTP to generate structured canonical reports.
The following figure depicts the Control Plane architecture and relations with other software items.