Building Effective Bridging Middleware for Legacy Systems: A Complete Guide
N
Back to Blog

Building Effective Bridging Middleware for Legacy Systems: A Complete Guide

Tutorial
Nugroho Setiawan · Konsultan IT & Full Stack Developer 13 Aug 2026 9 min baca 2,603 kata 280 views
Healthcare information systems are often hindered by data silos and difficulties integrating with modern standards. This article guides you in building robust bridging middleware to unify legacy systems such as older SIMRS with new platforms like BPJS, SatuSehat, and FHIR, improving interoperability

In this digital era, data interoperability has become the backbone of operational efficiency, especially in the healthcare sector. Many hospitals and clinics still rely on Hospital Management Information Systems (SIMRS) or Clinic Information Systems (SIM Klinik) that have been operating for decades. These legacy systems, although robust and familiar, are often a major obstacle to adopting modern standards such as SatuSehat (FHIR R4) or BPJS Kesehatan API integration, which are now regulatory and operational necessities. Common challenges include drastically different data models, outdated communication protocols (for example, SOAP or text formats), and a lack of adequate API documentation. As a result, IT teams are faced with a dilemma: carrying out a total, expensive, and risky system replacement, or continuously performing manual data entry that is error-prone and time-consuming. This article aims to provide practical solutions. We will guide you step by step in designing and implementing effective middleware bridging. With this approach, you can extend the life of legacy systems while opening the door to integration with the ever-evolving digital healthcare ecosystem, ensuring data flows smoothly, accurately, and securely, and meeting requirements such as Minister of Health Regulation (PMK) regarding interoperability standards.

Basic Concepts of Middleware Bridging for Legacy Systems

Middleware bridging is an intermediary software layer that serves to bridge communication and data exchange between different information systems, especially between existing legacy systems and new systems or standards. In the context of SIMRS or SIM Klinik, this middleware becomes crucial because old systems often have monolithic architectures, proprietary databases, and APIs that are incompatible with the latest industry standards such as FHIR R4 or the RESTful APIs used by BPJS Kesehatan and SatuSehat. Its main purpose is not to replace, but to extend the useful life of legacy systems by giving them the ability to "speak" with the modern outside world.

Imagine your old SIMRS as a sturdy old house but without an internet connection. Middleware bridging is the smart adapter you install, allowing that old house to connect to the modern internet network without having to overhaul the entire building structure. Key components of middleware bridging include: connectivity adapters, which can communicate with various protocols (for example, reading from an old SQL database, receiving HL7 v2.x messages, or calling a SOAP API); data transformation engines, which translate data formats from one system to another (for example, converting patient data structures from old database tables to the FHIR R4 Patient resource format); message routers, which direct data to the right destination based on business rules; error handling mechanisms, to manage transaction failures; and logging & monitoring modules, to track activity and performance.

Why is this approach preferred over "rip-and-replace"? First, the implementation cost of total system replacement can reach billions of rupiah and take years, with a high risk of operational disruption. Second, medical teams and administrative staff are already very accustomed to the workflow of legacy systems; drastic changes can reduce productivity. Third, middleware enables a gradual approach, in which integration can be done module by module or service by service. For example, you can start with patient registration integration to SatuSehat, then continue with observation or prescription data. This minimizes risk and provides business value incrementally.

Successful implementation of middleware bridging can significantly reduce duplicate data entry, minimize human error, accelerate business processes (for example, BPJS claims or data reporting to Kemenkes), and improve overall data quality. This is not only about meeting regulatory compliance, but also about creating a stronger data foundation for analysis, clinical decision-making, and future healthcare service innovation. With standards such as FHIR, supported by Kemenkes through SatuSehat, the need for such middleware is increasingly urgent to achieve true interoperability across the national healthcare ecosystem.

Technical Implementation Details of Middleware Bridging

Building robust middleware bridging requires careful architectural planning and the right technology selection. A commonly used architecture is microservices-based with an API Gateway. The API Gateway acts as a single entry point for all requests from or to legacy systems, managing authentication, authorization, and routing. Behind the gateway, various microservices can handle specific tasks such as data transformation, validation, and communication with external systems. To ensure resilience and scalability, we recommend using message queueing such as RabbitMQ (version 3.12.x) or Apache Kafka (version 3.6.x LTS) for asynchronous communication between microservices and handling non-instant transactions.

In terms of technology, PHP with the Laravel framework (version 11.x) is an excellent choice for building the main backend API of the middleware because of its rich ecosystem, complete documentation, and extensive community support. Laravel provides features such as Eloquent ORM for easy database interaction (for example with PostgreSQL 16.x), a queueing system, and tools for building RESTful APIs. For tasks that require high performance or complex data manipulation, Node.js (version 20 LTS) can be used for specific microservices, for example for an HL7 v2.x parser or a highly specific FHIR validator. Python can also be considered for intensive data transformation scripts.

Another crucial aspect is data mapping and transformation. This is the core of bridging. Data from legacy systems (for example, the NoRM, NamaPasien, TglLahir columns from the Pasien table) needs to be mapped and transformed into standard formats such as FHIR R4 (for example, Patient.identifier, Patient.name, Patient.birthDate). For XML transformation, XSLT is still relevant. However, for JSON (the main FHIR R4 format), it is recommended to write custom transformation scripts using languages such as PHP or Node.js. Libraries such as HAPI FHIR (version 6.8.x for Java) or `fhir-client` (for Node.js) are very helpful in parsing, validating, and generating appropriate FHIR R4 objects.

Security is non-negotiable. The middleware must implement strong security protocols. This includes the use of HTTPS/SSL for all communications, implementation of authentication and authorization (for example, OAuth2 for modern APIs, or API Keys for simpler systems), as well as encryption of sensitive data in transit and at rest (at rest). For integration with BPJS, ensure that you comply with their API security specifications. For SatuSehat, follow the strict FHIR R4 security guidelines. Storing audit log data is also important to track who accesses or modifies data.

Finally, deployment and monitoring. The middleware must be deployed in a scalable and resilient environment. The use of Docker (version 26.x) and orchestration with Docker Compose or Kubernetes (version 1.29.x) will be very helpful in managing various microservices and ensuring high availability. A comprehensive monitoring system (for example, Prometheus and Grafana for metrics, or the ELK Stack for logs) is essential to monitor performance, identify anomalies, and respond to issues proactively. This entire process must be integrated with a CI/CD (Continuous Integration/Continuous Deployment) pipeline to ensure fast and consistent releases.

Example of Middleware Bridging Implementation Code

This section will present concrete code examples that show how data from legacy systems can be received, queued, and then processed to be sent to external systems such as SatuSehat or BPJS. We will use PHP with Laravel 11.x for the receiving API and Node.js 20 LTS as the queue-processing worker.

1. API for Receiving Data from Legacy Systems (Laravel 11.x)

Suppose your legacy system can send patient data in a simple JSON format to a RESTful endpoint. The following Laravel code will receive that data, perform basic validation, and then send it to a queue for asynchronous processing. This is important so that the response to the legacy system is fast, and complex processing does not block the API.

<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; use App\Jobs\ProcessPatientData; class LegacyDataController extends Controller { public function receivePatientData(Request $request) { $validator = Validator::make($request->all(), [ 'NoRM' => 'required|string|max:20', 'NamaPasien' => 'required|string|max:255', 'TanggalLahir' => 'required|date', 'JenisKelamin' => 'required|in:L,P' ]); if ($validator->fails()) { return response()->json(['status' => 'error', 'message' => $validator->errors()], 400); } // Kirim data ke queue untuk diproses secara asinkron ProcessPatientData::dispatch($request->all()); return response()->json(['status' => 'success', 'message' => 'Data pasien diterima dan sedang diproses.'], 202); } } 

In the example above, ProcessPatientData is a Laravel Job that will handle the more complex data processing logic. By using a queue, the legacy system does not need to wait for the middleware to finish processing the data until it is sent to SatuSehat, which can take time. This improves system responsiveness and resilience.

2. Queue Processing Worker and Sender to SatuSehat (Node.js 20 LTS)

After the data enters the queue, a worker (for example, one running on Node.js) will take that data, transform it into FHIR R4 format, and send it to the SatuSehat API. We will use the axios library for HTTP requests and basic FHIR transformation concepts.

// worker.js
const amqp = require('amqplib'); // Untuk RabbitMQ
const axios = require('axios'); // Untuk HTTP requests ke SatuSehat
const SATU_SEHAT_API_URL = 'https://api-satusehat.kemkes.go.id/fhir-r4/v1';
const SATU_SEHAT_AUTH_URL = 'https://api-satusehat.kemkes.go.id/oauth2/v1/accesstoken';
const CLIENT_ID = process.env.SATU_SEHAT_CLIENT_ID;
const CLIENT_SECRET = process.env.SATU_SEHAT_CLIENT_SECRET;
let accessToken = null;
async function getAccessToken() {
  if (accessToken) return accessToken;
  try {
    const response = await axios.post(SATU_SEHAT_AUTH_URL, 'grant_type=client_credentials', {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      auth: {
        username: CLIENT_ID,
        password: CLIENT_SECRET
      }
    });
    accessToken = response.data.access_token;
    return accessToken;
  } catch (error) {
    console.error('Error getting access token:', error.message);
    throw error;
  }
}

async function transformToFhirPatient(legacyData) {
  // Contoh transformasi sederhana, perlu disesuaikan dengan mapping nyata
  const gender = legacyData.JenisKelamin === 'L' ? 'male' : 'female';
  return {
    resourceType: 'Patient',
    identifier: [{
      system: 'http://sys-legacy.com/norm',
      value: legacyData.NoRM
    }],
    name: [{
      use: 'official',
      text: legacyData.NamaPasien
    }],
    gender: gender,
    birthDate: legacyData.TanggalLahir
  };
}

async function sendToSatuSehat(fhirPatient) {
  try {
    const token = await getAccessToken();
    const response = await axios.post(`${SATU_SEHAT_API_URL}/Patient`, fhirPatient, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });
    console.log('Successfully sent to SatuSehat:', response.data.id);
    return response.data;
  } catch (error) {
    console.error('Error sending to SatuSehat:', error.response ? error.response.data : error.message);
    throw error;
  }
}

async function startWorker() {
  try {
    const connection = await amqp.connect('amqp://localhost'); // Ganti dengan URL RabbitMQ Anda
    const channel = await connection.createChannel();
    const queue = 'patient_data_queue';
    await channel.assertQueue(queue, { durable: true });
    console.log(`Worker waiting for messages in ${queue}. To exit press CTRL+C`);

    channel.consume(queue, async (msg) => {
      if (msg !== null) {
        try {
          const legacyData = JSON.parse(msg.content.toString());
          const fhirPatient = await transformToFhirPatient(legacyData);
          await sendToSatuSehat(fhirPatient);
          channel.ack(msg); // Konfirmasi bahwa pesan telah diproses
        } catch (error) {
          console.error('Error processing message:', error.message);
          channel.nack(msg); // NACK pesan, mungkin akan diulang atau masuk DLQ
        }
      }
    }, { noAck: false });
  } catch (error) {
    console.error('Failed to start worker:', error.message);
  }
}

startWorker();

This Node.js code shows how the worker retrieves messages from the RabbitMQ queue, transforms legacy patient data into the FHIR R4 Patient resource format, obtains a SatuSehat access token, and then sends it to the SatuSehat API. The ack and nack mechanisms in RabbitMQ are important to ensure that messages are not lost if processing fails. This is the foundation of a resilient system.

Robust Data and Error Handling

In system integration, especially with highly sensitive and complex health data, robust data and error handling is key. Invalid data or errors during transmission can cause serious problems, ranging from inaccurate data in patient medical records to insurance claim failures. Therefore, middleware bridging must be designed with careful validation, transformation, and error handling mechanisms.

Let's look at an example of a realistic data payload in FHIR R4 format for a Patient resource that will be sent to SatuSehat, and how potential errors can arise and how to handle them.

For example, a valid FHIR Patient payload must contain mandatory elements such as resourceType, identifier (NIK or medical record number), name, gender, and birthDate. If any of these elements are missing or incorrectly formatted, SatuSehat will return a 400 error. The middleware must validate the payload before sending, for example with JSON Schema or a FHIR validation library, so that errors can be caught earlier and do not burden the destination API.

In addition to validation, implement a retry strategy with exponential backoff for temporary errors (e.g., timeout or 5xx), and send directly to a Dead Letter Queue (DLQ) for permanent errors (e.g., 400 due to invalid data). That way, failed messages will not be lost and can be re-analyzed by the operations team.

Practical Tips for Building Effective Middleware Bridging

First, start with a clear data contract. Define the transformation schema between the legacy system and the destination standard (FHIR, HL7, or specific API) from the beginning. Use tools such as a mapping table or transformation DSL so that changes in business rules do not force you to change the core code. Document every field, including code conversions (e.g., ICD-9 to ICD-10) and null value handling.

Second, separate concerns: create separate layers for legacy connectors, transformation, validation, and delivery. This facilitates unit testing and component replacement. Use the idempotent consumer pattern by storing the IDs of messages that have been processed, so that re-delivery does not produce duplicate data in the destination system. For audit, record every message status change along with timestamp and payload hash.

Third, set up observability and alerting. Monitor metrics such as throughput, latency, number of messages in the DLQ, and error rate. Integrate with monitoring systems (Prometheus, Grafana, or cloud watch) and send notifications to the team if thresholds are exceeded. Also perform light chaos testing, for example temporarily shutting down the connection to the destination API, to ensure the retry and fallback mechanisms work as planned.

FAQ

Does bridging middleware always have to use a message broker such as RabbitMQ?

Not always. A message broker is very helpful for decoupling, buffering, and reliability, especially if data volume is high or the legacy system is not always online. However, for simple integrations with low volume, a synchronous approach via REST or scheduled batch can be easier. Choose based on scalability requirements, fault tolerance, and operational complexity.

How to handle date format differences between legacy systems and FHIR?

Normalize dates to ISO 8601 format (YYYY-MM-DD) for FHIR. If the legacy system stores dates in local format or Unix timestamp, create a centralized conversion function and test it with various time zones. Also ensure the handling of incomplete dates (for example, year only) complies with FHIR rules, for example using birthDate with permitted precision.

Is it necessary to store raw data from legacy systems?

Preferably yes, store raw data (raw payload) in separate storage such as object storage or an audit database, with encryption and strict access controls. This is useful for troubleshooting, reprocessing, and audit compliance. Ensure data retention policies comply with applicable personal data protection regulations.

How to test middleware before production?

Perform layered testing: unit tests for transformation and validation, integration tests with a mock destination API, and end-to-end tests in a staging environment that resembles production. Use test data covering normal cases, edge cases (for example, names with special characters), and failure scenarios. Also simulate network failures to verify retry and DLQ behavior.

Conclusion

Building effective bridging middleware for legacy systems requires a combination of the right architecture, careful data handling, and operations ready to face failures. By adopting a message broker, strict validation, retry strategies, and good observability, you can connect old systems to modern ecosystems such as SatuSehat without sacrificing data reliability and security. Investment in this design will save time and maintenance costs in the long run.

If you need help designing or implementing bridging middleware that fits your organization's needs, our team is ready to help. Consult your integration needs now and get a secure, scalable, and regulation-compliant solution.

This article is part of the education by Nugroho Setiawan, an IT consultant in Jogja. Related solutions: SIMRS BPJS & SatuSehat Bridging Integrator. Need a free consultation?

Terakhir diperbarui 18 Oct 2026

Komentar

Komentar ditinjau sebelum tampil.

Belum ada komentar. Jadilah yang pertama!

Butuh bantuan implementasi atau dashboard data?

Saya membantu konsultasi IT, pengembangan aplikasi, dan visualisasi data untuk rumah sakit, klinik, dan bisnis di Yogyakarta (DIY), Magelang, dan sekitarnya.

WhatsApp Jasa Visualisasi Data Demo VizStudio
Produk & Solusi SIMRS ERP Portfolio Konsultasi Gratis