<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Madhukumarap on Medium]]></title>
        <description><![CDATA[Stories by Madhukumarap on Medium]]></description>
        <link>https://medium.com/@madhukumarap07?source=rss-0374beb2ad23------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*d4-oXetoJZj9xx73</url>
            <title>Stories by Madhukumarap on Medium</title>
            <link>https://medium.com/@madhukumarap07?source=rss-0374beb2ad23------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:50:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@madhukumarap07/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Reliable DICOM Processing Pipeline with Python, FastAPI, SQLite, and MySQL]]></title>
            <link>https://medium.com/@madhukumarap07/building-a-reliable-dicom-processing-pipeline-with-python-fastapi-sqlite-and-mysql-b8fe5ae24b80?source=rss-0374beb2ad23------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8fe5ae24b80</guid>
            <category><![CDATA[dicom]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[fastapi-dicom-service]]></category>
            <dc:creator><![CDATA[Madhukumarap]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 10:25:31 GMT</pubDate>
            <atom:updated>2026-11-17T10:25:31.682Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Reliable DICOM Processing Pipeline with Python, FastAPI, SQLite, and MySQL</h3><p><em>How I designed an asynchronous DICOM ingestion service while reusing an existing healthcare database architecture.</em></p><h3>Introduction</h3><p>Healthcare applications generate and process large amounts of medical imaging data. DICOM (Digital Imaging and Communications in Medicine) is one of the most widely used standards for storing and exchanging medical images.</p><p>While working on the HeartNet platform, I worked on designing a dedicated Python-based DICOM processing service.</p><p>The objective was not simply to upload a DICOM file and save it somewhere. The service needed to validate medical imaging metadata, identify the correct institution and user, register patient and study information in an existing MySQL database, and store the original DICOM file in a structured directory.</p><p>Another important requirement was to maintain compatibility with the existing HeartNet Gateway and its database procedures.</p><p>This article explains the problem, architecture, design decisions, implementation and lessons learned.</p><h3>1. The Problem: Why Did We Need a Dedicated DICOM Service?</h3><p>The existing application already had a Gateway service responsible for handling several backend operations.</p><p>However, we wanted to separate DICOM-specific processing into a dedicated Python service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2ejw7RI2ZCTSpbwBCSJhg.png" /></figure><p>There were several engineering challenges:</p><h3>Challenge 1: Synchronous file processing</h3><p>Processing a DICOM file involves multiple operations:</p><ul><li>Reading the DICOM dataset.</li><li>Extracting patient and study metadata.</li><li>Validating institution and user information.</li><li>Checking for duplicate studies.</li><li>Registering records in the database.</li><li>Storing the original DICOM file.</li></ul><p>Performing all these operations within a single HTTP request can make the API wait until processing finishes.</p><p>This becomes particularly problematic when multiple files are uploaded.</p><h3>Challenge 2: Metadata validation</h3><p>The service needed to identify the institution and user associated with each DICOM file.</p><p>We used custom DICOM private tags:</p><ul><li>Institution GUID: (0029,1002)</li><li>User GUID: (0029,1001)</li></ul><p>Missing or invalid metadata could prevent the registration process from continuing.</p><h3>Challenge 3: Existing database compatibility</h3><p>HeartNet already had an established MySQL database schema and stored procedures.</p><p>Rebuilding the registration logic would introduce unnecessary changes and additional risks.</p><p>The new service needed to reuse the existing database workflow.</p><h3>Challenge 4: Reliable processing</h3><p>What happens if the application restarts while a DICOM file is being processed?</p><p>What happens if a database connection temporarily fails?</p><p>We needed a queue, retry mechanism and job tracking system to handle these situations.</p><h3>Challenge 5: File organization</h3><p>Saving all DICOM files in a single directory makes retrieval and management difficult.</p><p>We needed a predictable directory structure and readable filenames.</p><h3>2. Designing the Solution</h3><p>I designed a separate DICOM processing service using:</p><p>TechnologyResponsibilityPythonCore processing logicFastAPIREST APIpydicomDICOM metadata extraction and validationSQLitePersistent processing job queueMySQLExisting HeartNet databaseBackground workerAsynchronous DICOM processingpathlib / shutilFile and directory management</p><p>The important architectural decision was to separate file reception from file processing.</p><p>Instead of making the client wait for the entire registration process, the API accepts the file, creates a job and returns a job ID.</p><p>The background worker handles the remaining operations.</p><h3>3. System Architecture</h3><p>The high-level architecture looks like this:</p><pre>flowchart TD<br>    A[React Client] --&gt;|Upload DICOM| B[FastAPI Service]<br>    B --&gt; C[Temporary Upload Folder]<br>    B --&gt; D[SQLite Job Queue]<br>    D --&gt; E[Background Worker]<br>    E --&gt; F[DICOM Metadata Extraction]<br>    F --&gt; G[Institution and User Validation]<br>    G --&gt; H[HeartNet MySQL Database]<br>    H --&gt; I[Existing Stored Procedures]<br>    I --&gt; J[Patient / Study / Series / Image Registration]<br>    J --&gt; K[Institution DICOM Storage]<br>    E --&gt; L[Job Status and Retry Updates]<br>    L --&gt; D<br>    B --&gt; M[Job Status API]<br>    M --&gt; D</pre><p>The architecture has four main parts:</p><ol><li>API layer</li><li>Persistent job queue</li><li>Background processing worker</li><li>Existing MySQL database and DICOM file storage</li></ol><p>Each component has a specific responsibility.</p><h3>4. Implementing Asynchronous Processing with FastAPI</h3><p>The first important design decision was to avoid processing the complete DICOM file inside the upload request.</p><p>The upload API saves the file in a temporary directory and adds a processing job to SQLite.</p><p>The API returns HTTP 202 Accepted.</p><p>Example response:</p><pre>{<br>  &quot;success&quot;: true,<br>  &quot;jobId&quot;: &quot;generated-job-id&quot;,<br>  &quot;status&quot;: &quot;pending&quot;,<br>  &quot;fileName&quot;: &quot;sample.dcm&quot;<br>}</pre><p>This means the request has been accepted, but processing has not necessarily completed.</p><p>The client can use the returned job ID to check the processing status.</p><h3>Why HTTP 202?</h3><p>It allows the client to continue working without waiting for database registration and file storage to finish.</p><p>This also separates two different operations:</p><ul><li>Receiving a DICOM file.</li><li>Processing and registering a DICOM file.</li></ul><p>That separation makes the application easier to maintain.</p><h3>5. Why I Chose SQLite for the Queue</h3><p>One of the important decisions was selecting a queue storage mechanism.</p><p>Initially, an in-memory Python queue was an option.</p><p>However, an in-memory queue has a major limitation: jobs can be lost when the application restarts.</p><p>For this implementation, I selected SQLite.</p><p>SQLite stores job information in a local database file without requiring a separate database server.</p><p>The queue maintains information such as:</p><ul><li>Job ID</li><li>Uploaded file path</li><li>Processing status</li><li>Retry count</li><li>Error message</li><li>Final stored file path</li><li>Creation and update timestamps</li></ul><p>The processing lifecycle looks like this:</p><pre>PENDING<br>   |<br>   v<br>PROCESSING<br>   |<br>   +---- Success ----&gt; COMPLETED<br>   |<br>   +---- Temporary error ----&gt; RETRY<br>   |<br>   +---- Retry limit reached ----&gt; FAILED</pre><p>An important advantage is that pending jobs can be recovered when the service starts again.</p><p>Jobs left in the processing state after an unexpected interruption can also be recovered.</p><p>One limitation is that SQLite is not intended to provide unlimited concurrent writes. For a single-server service with a controlled worker count, it is a lightweight starting point.</p><h3>6. DICOM Metadata Extraction and Validation</h3><p>Before inserting records into the database, the service needs to extract the required metadata.</p><p>I used pydicom to read the DICOM dataset.</p><p>For example:</p><pre>import pydicom</pre><pre>ds = pydicom.dcmread(file_path)</pre><pre>patient_id = str(<br>    getattr(ds, &quot;PatientID&quot;, &quot;&quot;)<br>).strip()</pre><pre>study_uid = str(<br>    getattr(ds, &quot;StudyInstanceUID&quot;, &quot;&quot;)<br>).strip()</pre><pre>sop_uid = str(<br>    getattr(ds, &quot;SOPInstanceUID&quot;, &quot;&quot;)<br>).strip()</pre><p>The service also reads the custom institution and user GUID tags.</p><p>These identifiers are used to validate the context against the existing HeartNet database.</p><h3>Institution validation</h3><p>The institution GUID is checked against:</p><p>cmr_inst_master</p><h3>User validation</h3><p>The user identifier is checked against:</p><p>cmr_user_master</p><p>The service verifies that the institution and user are valid and active before proceeding.</p><p>This prevents invalid DICOM context from reaching the registration stage.</p><h3>7. Reusing Existing MySQL Stored Procedures</h3><p>One of the most important design decisions was reusing the existing HeartNet database procedures rather than implementing a completely new registration workflow.</p><p>The service uses the following stored procedures:</p><p>Stored procedureResponsibilityusp_InsertPatientRecordPatient registrationusp_InsertStudyRecordStudy registrationusp_InsertSeriesRecordSeries registrationusp_insertimagerecordDICOM image registration</p><p>The processing sequence is:</p><ol><li>Validate institution and user.</li><li>Resolve or create the patient.</li><li>Check whether the study already exists.</li><li>Insert the study if required.</li><li>Insert or resolve the series.</li><li>Register the DICOM image.</li><li>Store the original DICOM file.</li></ol><p>Reusing these procedures helped maintain compatibility with the existing application.</p><p>It also avoided duplicating business logic across two services.</p><p>An important production consideration is ensuring that retries do not create duplicate records. Each registration step should have appropriate duplicate checks and idempotency safeguards.</p><h3>8. Retry Mechanism and Error Handling</h3><p>A reliable processing service needs to distinguish between temporary failures and permanent input errors.</p><p>For example:</p><p><strong>Temporary failures:</strong></p><ul><li>MySQL connection failure.</li><li>Database timeout.</li><li>Temporary file access error.</li></ul><p>These may succeed when retried.</p><p><strong>Permanent failures:</strong></p><ul><li>Missing Institution GUID.</li><li>Missing User GUID.</li><li>Invalid DICOM metadata.</li><li>Unsupported SOP Class.</li></ul><p>Repeating an unchanged invalid file will not fix these problems.</p><p>After the configured retry limit, permanently failed files are moved to the invalid DICOM directory and their job status is updated.</p><p>The queue also retains error information for troubleshooting.</p><p>This distinction is important because retrying every error wastes processing resources.</p><h3>9. Organizing DICOM File Storage</h3><p>Another important part of the implementation was designing a predictable directory structure.</p><p>The service uses a configurable root directory:</p><pre>DCMIMG_FOLDER_PATH=D:/heartnet/dcmimg/d-dicom</pre><p>The institution, patient, study and series identifiers are used to organize the files.</p><p>Example:</p><pre>d-dicom/<br>└── Institution_Name/<br>    └── Patient_ID/<br>        └── Study_ID/<br>            └── Series_ID/<br>                └── DICOM_FILE.dcm</pre><p>This makes it easier to locate files using their corresponding database records.</p><h3>Meaningful file naming</h3><p>I also wanted filenames to be understandable without opening the DICOM file.</p><p>The selected naming convention is:</p><pre>P{PatientID}_I{InstitutionID}_ST{StudyID}.dcm</pre><p>For example:</p><pre>P12345_I1001_ST70001.dcm</pre><p>This provides a readable reference to the patient, institution and study.</p><p><strong>Important design consideration:</strong> This short filename is suitable only when there is one file per such identifier combination. Real DICOM studies can contain multiple images, so a production deployment must handle filename collisions, for example by adding a unique SOP Instance UID or another unique suffix.</p><h3>10. Job Status API for the Client</h3><p>The React client should not need to know how the background worker operates.</p><p>It only needs a job ID and a way to retrieve the status.</p><p>I designed the status endpoint as:</p><pre>GET /api/v1/dicom/status/{jobId}</pre><p>Possible statuses:</p><p>StatusMeaningpendingWaiting in the queueprocessingCurrently being processedcompletedRegistration and file storage succeededfailedProcessing failed permanently</p><p>Example completed response:</p><pre>{<br>  &quot;jobId&quot;: &quot;generated-job-id&quot;,<br>  &quot;status&quot;: &quot;completed&quot;,<br>  &quot;result&quot;: {<br>    &quot;patientId&quot;: 12345,<br>    &quot;institutionId&quot;: 1001,<br>    &quot;studyId&quot;: 70001,<br>    &quot;seriesId&quot;: 80001,<br>    &quot;imageId&quot;: 90001,<br>    &quot;fileName&quot;: &quot;P12345_I1001_ST70001.dcm&quot;<br>  }<br>}</pre><p>For a production client, I would expose an authenticated</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8fe5ae24b80" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>