Intelligent Sleep Monitoring System Based on Microservices and Event-Driven Architecture

Sleep monitoring using polysomnography (PSG) in hospitals can be considered expensive, so the preferable way is to use contactless and wearable sensors to monitor sleep daily by patients at home. In this study, the Internet-of-Things (IoT) platform was utilized for sleep monitoring with contactless or wearable sensors as an integrated system developed based on an event-driven and microservice architecture. Multiple services that respond to events are provided within the system. Electrocardiogram (ECG) data were used as the input in the sleep monitoring system. The combination of the weighted extreme learning machine (WELM) algorithm with particle swarm optimization (PSO) was used to process the ECG data, followed by fuzzy logic to measure sleep quality, then display the data on the dashboard. Based on the experimental results, the proposed architecture increased throughput by 34.76%, decreased response time by 55.85%, and reduced memory consumption by 37.26% per instance replication compared to the non-event-driven architecture. The accuracies of the sleep stage classification were 78.78% and 73.09% for the three and four classes, respectively, and the area under a receiver operating characteristic (ROC) curve (AUC) reached 0.89 for both the three and four class classifications.


I. INTRODUCTION
A behavioral state of low awareness or consciousness of the environment can be defined as sleep, in which muscles enter a relaxed state while the human nervous system becomes inactive [1]. Sleep is essential for restoring the body and mind to their original state. Physical and psychological problems such as dizziness and work accidents may occur because of poor sleep quality [2]. As a solution, a sleep monitoring system can be used for the early detection of sleep disorders.
Integrating several technologies, such as sensors, cloud computing, and mobile technology is required for the Internet of things (IoT) in sleep monitoring systems. IoT connects humans with devices and/or digital services, providing a platform for sensor, data processing, and dashboard integration.
The associate editor coordinating the review of this manuscript and approving it for publication was Shadi Alawneh .
Hence, sleep data can be easily accessed by the corresponding personnel to monitor and analyze the sleep quality of patients.
Sleep monitoring systems can be designed using several types of architecture [2]- [5]. Typically, three main parts are deployed in the IoT architecture for sleep monitoring: 1) a sensor gateway to gather data, 2) an IoT platform to save and handle data from sleep quality sensors, and 3) dashboards for patients and health experts.
Two concepts can be used to improve the performance of IoT backend services in software architecture technology: event-driven and microservices. In the microservices concept, the system is divided into several independent microservices defined by each function. Microservices consist of components that can be developed and deployed individually using low inter-service coupling to improve the software development process and increase the resource usage efficiency of the servers [6]. In an event-driven concept, events trigger, determine, and build the flow of the system [7]. VOLUME 10, 2022 This work is licensed under a Creative Commons Attribution 4.0 License. For more information, see https://creativecommons.org/licenses/by/4.0/ Event consumers and producers can be decoupled using an event-driven architecture. Communication between producers and consumers, such as routing messages, maintaining topics, and validating messages, can be facilitated by a message broker [8], [9]. Asynchronous processing occurs in an event-driven architecture where a direct connection between the producer and consumer is not possible, resulting in dependency reduction between services and functional capability maximization of each service.
The quantification system for sleep quality is a part of the proposed sleep monitoring system. In 1989, Buyese et al [10] determined sleep quality using the Pittsburgh Sleep Quality Index (PSQI) via sleep quality questionnaires based on onemonth sleep experience. In 2017, Ang et al. [11] used a fuzzy system to quantify sleep quality based on deep sleep, total sleep, and wake duration during a one-night sleep. Total of 27 sets of rules were used to define nine levels of sleep quality.
A classification system is required to classify the sleep stages. Several physiological signals from sensors such as electrocardiography (ECG), electroencephalography (EEG), electromyography (EMG), and electrooculography (EOG) are commonly used by researchers. ECG signals are preferable for sleep studies because they can provide accurate sleep stage classification with simplicity [12]- [17]. Support vector machines (SVMs), Bayesian networks, and deep learning algorithms have been deployed for classification using ECG signals. Based on Moorcroft [1], sleep stages are divided into unequal proportions or imbalanced distributions, resulting in inaccurate classifications. Class distributions of 30.5%, 6.89%, 1.78%, 4.76%, 38.28%, and 17.79% for awake, rapid eye movement (REM), non-rapid eye movement (NREM)4, NREM3, NREM2, and NREM1 stages, respectively, were included in the MIT-BIH polysomnographic database used in this study. A weighted extreme learning machine (WELM) can solve imbalanced dataset problem [18]. WELM is an extreme learning machine (ELM) algorithm with a weight matrix for strengthening the minority class and weakening the majority class.
The incremental contributions in this research are: 1) IoT architecture with applied microservices and eventdriven concepts.
2) The combination of WELM with particle swarm optimization (PSO) algorithm was used to classify the sleep stage. 3) Mobile-based dashboard for personal sleep monitoring to display sleep quality data for use by health practitioners. Good performance (as in better classification accuracy, area under a receiver operating characteristic (ROC) curve (AUC), throughput, memory allocation, and response time) is expected using the novel methods described above. This paper is an extended version of the conference proceedings published in [19].
The remainder of this paper is structured as follows: Section 2 includes the works related to sleep monitoring systems. Section 3 contains information on the proposed IoT platform and the sleep stage classification algorithm, whereas Section 4 presents the proposed sleep-monitoring dashboard. Section 5 provides the performance evaluation of the proposed system, and finally, Section 6 presents the conclusions and future work to complete the paper.

II. RELATED WORK
Software architecture, sleep stage classification, and sleep quality quantification were included in this study. Hence, related work is outlined.

A. THE ARCHITECTURE OF SLEEP MONITORING SYSTEM
Surantha et al. [2] surveyed the design of IoT-based sleep monitoring consisting of several parts: 1) data acquisition from sensors, 2) a data aggregator transmitting data to the cloud server, 3) cloud processing for data processing, and 4) an analytics dashboard for application-based monitoring.
In 2016, Kim et al. [3] used cloud-based sensing (Sense-Cloud) as a service (CSaaS), as shown in Fig. 1. Using SenseCloud, users can register sensors, and the sensor data can be stored in SenseCloud storage. In SenseCloud, each service is dedicated to a specific function. The sensor gateway that received data from the sensor was operated using cloud virtual machines and stored in the sensor database. The architecture in this study is denoted as the microservices database (McsDB).
An IoT-based smart healthcare system collecting various sensor data used by health practitioners was developed in 2019 [4], [5] using the architecture shown in Fig. 2. Multiple functions are served by the cloud application, such as 1) obtaining data and information from the sensor gateway, 2) saving the data to the database, and 3) performing data processing. This smart healthcare architecture is denoted as the monolithic architecture (MnlDB) in this work.

B. THE QUANTIFICATION OF SLEEP QUALITY
Ang et al. [11] used a fuzzy logic algorithm to quantify sleep quality, taking the percentage of total sleep, deep sleep, and awake duration as input, then categorizing it into bad, good, and sufficient. Three categories were quantified into nine levels of sleep quality, from the worst (L1) to best (L9) using several sets of rules, in which this study was also implemented using the jFuzzyLogic Java library [20].

C. THE CLASSIFICATION OF SLEEP STAGE
Before quantifying sleep quality, Ang et al. [11] used ECG data as inputs to acquire sleep stages. The classification of sleep stages has been conducted using several algorithms.
Adnane et al. [12] classified sleep stages into two classes: awake and sleep, with an accuracy of 79.99% using the SVM method. The MIT-BIH polysomnographic database was used as a dataset with ten extracted features. Xiao et al. [13] used a random forest algorithm to classify three classes of sleep stages: REM, awake, and NREM. An accuracy of 88.67% was achieved using 41 features.
Another approach was proposed by Fonseca [14] in 2015 using the Bayesian Network multi-class method to classify PSG data into three classes and four classes of sleep stages: awake, REM, deep sleep, and light sleep. For three and four classes, the obtained accuracies were 80% and 69%, respectively, using 80 features.
In 2016, Lesmana et al. [15] classified sleep stages using a combination of ELM and PSO algorithms. A total of 18 features from the MIT-BIH polysomnographic database were utilized and achieved accuracy rates of 62.66%, 71.52%, 76.77%, and 82.1% for six, four, three, and two classes, respectively. The accuracy rate of 62.66%, 71.52%, 76.77%, 82.1% was obtained for 6, 4, 3, 2 classes. PSO was used for feature selection, and the ELM algorithm was used to calculate the fitness value. Yücelbaş [16] deployed a morphological method to classify 3 classes of sleep stages using 15 features. The MIT-BIH polysomnographic databases and polysomnography (PSG) were used as datasets with 77.02% accuracy. Wei et al. [17] used a deep neural network to classify the three classes using the MIT-BIH polysomnographic database data. An accuracy of 77% was obtained for the 11 features. Table 1 summarizes the related work on sleep classification algorithms.
In the research conducted by Lesmana et al. [15], 70% of the dataset was used for training and the rest for testing, using 18 features extracted from ECG data every 30 s. The features are divided into 11 time-domain features and 7 frequency-domain features [16]. Frequencydomain features consist of 1) Total power, 2) low-frequency range (0.04 Hz to 0.15 Hz) (LF), 3) total power in the very-low-frequency range (≤0.04 Hz) (VLF), 4) highfrequency range (0.15 Hz to 0.4 Hz) (HF), 5) LF and HF power in normalized units, and 6) ratio of LF and HF. Meanwhile, the 11 features of time-domain [21] consist of the following: 1) average of RR intervals (AVNN), 2) standard deviation of RR intervals (SDNN), 3) root mean square of the differences of adjacent RR intervals (RMSSD), 4) standard deviation of differences between adjacent RR intervals (SDSD), 5) count of successive differences of RR intervals for more than 50 ms (NN50), 6) the division of NN50 and the total of RR intervals minus 100 in percentage (pNN50), 7) HRV Triangular Index, 8) standard deviation of points which is perpendiculars to the axis of line of identity (SD1), 9) along the axis of line of identity (SD2), 10) ratio of SD1 and SD2, and 11) area of ellipse [21].
In 2013, Zong et al. [18] deployed WELM algorithm using weight matrix to solve the imbalanced class distribution. The weight matrix (W), which is a diagonal matrix with its elements, is shown in (1).
The use of the weight element helps the model to deal with the imbalanced class distribution by weakening the majority class and strengthening the minority class, also immediately compensating with the C-constant of the ELM optimization problem. The WELM optimization using the additional weight matrix is shown in (2). minimize: Each class was mapped into an array with m elements for m multiclass classification. Each element had a value of either −1 or 1, where the targeted class had a value of 1. The WELM algorithm used for testing and training is illustrated in Fig. 3.

III. THE PROPOSED SYSTEM ARCHITECTURE AND SLEEP STAGE CLASSIFICATION ALGORITHM
This study aimed to develop a sleep monitoring system using event-driven and microservices architecture with satisfactory performance based on memory allocation, response time, and throughput. In addition, the combination of WELM and PSO algorithms to achieve better sleep classification accuracy is also provided. The sleep monitoring system via the IoT architecture with microservices and event-driven is shown in Fig. 4. The system consists of data acquisition and monitoring applications integrated into the IoT cloud server. The microservice applications on each IoT platform block had their source code, independent from other applications, and could be deployed separately.
The MIT-BIH polysomnographic data were streamed and used as sensor simulation data in the data acquisition process. The proposed IoT platform has five functions for sleep monitoring: 1) receiving incoming data and information from the sensor, 2) saving data to the database, 3) classifying the sleep stages, 4) measuring sleep quality, and 5) visualizing the sleep data to the dashboard.
The sensor gateway was deployed to receive data, whereas the sensor data were persistent for storing data. Message brokers were used for the communication. After receiving the sensor data, the sensor gateway publishes an event and stores it using sensor data persister. Data ingestion and storage were performed separately and asynchronously through service separation.
After receiving and saving the sensor data in the database, sleep stage classification was carried out using the WELM and PSO algorithm combination. The process also involves scheduling a system to check the available data in the database. An event was published when the classification process finished and responded to using a fuzzy algorithm to quantify sleep quality.
Finally, sleep quality data were be retrieved from the database and displayed on the dashboard. The proposed service also provides administrative features such as patient registration.

A. FIRST PART: THE SENSOR GATEWAY
An IoT platform related to sensors for sleep monitoring is a sensor gateway. The representational state transfer (REST) protocol [22] was used with an additional security layer using the JSON Web Token (JWT) [23], [24]. The patient was identified using the request body, which consisted of the ECG data and the patient's unique sensor token. The message broker was then received the data with ''ecgDataInput'' topic, as shown in Fig. 5. The asynchronous and separated process of the data storing and receiving process resulted from the event-driven and microservices architecture. The implementation expected a lower response time and a higher throughput in the sensor gateway. The ''ecgDataInput'' event was used to trigger the sensor data persister to validate and keep the data in the SQL database. The consumer group in the event-driven architecture was used as a concept for designing the sensor data persister; hence, replication to process large amounts of data from the sensor gateway was prepared.
Every patient had only one sleep quality data because only one set of ECG data was processed each day. The ECG data processing time was determined using a time range field during the patient registration process. Fig. 6 shows the flowchart of the sensor data persister. The combined WELM and PSO algorithms were deployed for sleep stage classification as an upgrade to the combination of ELM and PSO algorithms by Lesmana et al. [15]. The ELM-PSO combination was deployed as a reference because of its quick learning time while maintaining a high generalization performance. The MIT-BIH database of human sleep ECG recordings [25] containing 10274 samples of 18 recording files was used as the dataset for classification. After removing invalid annotations or time, 10154 valid data were obtained. In every 30 seconds segment, six sleep stages were denoted in the MIT-BIH data samples, further mapped into three or four classes. The data distribution obtained for the three classes were wake (30.5%), REM (6.89%), and NREM (62.61%), whereas for the four classes were wake (30.5%), REM (6.89%), deep sleep (NREM3 and NREM4) (6.54%), and light sleep (NREM1 and NREM2) (56.07%). The dataset was then divided into 70:30 proportions as training and testing data, following the method described by Lesmana et al. [15].
Feature selection was carried out using the PSO algorithm to choose the best subset features because of the reduced selected features that affect processing time, resulting in a better and faster sleep stage classification [26]. The position of the PSO particle to represent the masked feature is designated by binary coding. The 18 features consist of seven frequency-domain features and 11 time-domain features [16]. The employed frequency-domain features are total power (TP), total power in the very low frequency range (≤0.04 Hz) (VLF), low frequency range (0.04 Hz to 0.15 Hz) (LF), high frequency range (0.15 Hz to 0.4 Hz) (HF), ratio of LF and HF, LF, and HF power in normalized units. Meanwhile, the time-domain features are: 1) RR interval average (AVNN), 2) RR intervals' standard deviation (SDNN), 3) square root of the average squared differences of adjacent NN intervals (RMSSD), 4) standard deviation of differences between adjacent RR intervals (SDSD), 5) count of successive differences of RR intervals that are more than 50ms (NN50), 6) the division of NN50 and the total of RR intervals minus 100 (pNN50), 7) HRV triangular index, 8) standard deviation of points perpendicular to the axis of line-of-identity (SD1) and 9) along the axis of line-of-identity (SD2), 10) ratio of SD1 and SD2, and 11) area of ellipse [21]. Following the work of Malik et al. [21], 18 bits were deployed to represent 18 extracted features, yielding 262144 particles. For instance, a particle with a position of 215176 (110100100010001000 in binary) indicates that feature numbers 1, 2, 4, 7, 11, and 15 are the selected features. Fig. 7 shows a flowchart of the combined WELM and PSO algorithms. In the testing dataset, model accuracy was the calculated fitness value. WELM was deployed to calculate the accuracy of each particle as a fitness function. A total of 80 sets of 20 particles with 20 iterations were used, whereas the c 1 and c 2 for PSO was 1.2 as stated in [15].
The flowchart can be explained as follows: 1. Dividing the dataset to 70:30 for the ratio of training and testing. 2. Initializing P particle with I iteration. 3. Initializing 262144 particle positions with the value of 0. 4. Decoding the position of the particle, obtaining, and masking each particle's features. 5. Calculating fitness value using WELM, which is used for testing accuracy. 6. Updating pBest (local) and gBest(global) 7. Updating particle velocity, including its new position. Fig. 8 shows a flowchart of the SSCS scheduler and validation algorithm, in which two validations were run every second on the database. After the sleep time range, ECG data were no longer recorded for the day. Then, the classification process is carried out based on the testing phase in Fig. 3, with the w matrix, β matrix, and selected features of the learning process using a combination of WELM and PSO. The ''sleepStageReady'' event would be published by sleep stage classification service after finishing the sleep quality classification.

D. FOURTH PART: SLEEP QUALITY QUANTIFICATION SERVICE (SQQS)
The sleep quality level was quantified using a fuzzy algorithm [11] based on the awake, deep sleep, and total sleep duration percentage in the sleep quality quantification service (SQQS). Fig. 9 shows a flowchart of the event-based concept in the SQQS.
The process of sleep quality quantification was executed by the ''sleepStageReady'' event from the SSCS. The work of Ang et al. [11], which used the jFuzzyLogic library, was deployed in which the awake, deep sleep, and total sleep duration from the SSCS were used as fuzzy inputs. A set of data for metrics or extra information on the dashboard was calculated from the sleep stages in SQQS, such as the duration of awake, light sleep, deep sleep, total sleep, REM, as well as VOLUME 10, 2022   In addition to acting as a gateway for the application, it also facilitated the registration of patients and health practitioners. A sensor token is generated using a universally unique identifier (UUID) in the patient registration process [27]. REST endpoints were provided by this service to retrieve the ECG, sleep quality, and sleep stage information for each patient.

F. SIXTH PART: APPLICATION MONITORING
A mobile-based application for clients or patients is used for monitoring application. Tables and graphs were created to  present informative sleep data on the dashboard regarding the details of patient sleep.

IV. PROPOSED MONITORING DASHBOARD
The proposed dashboard was built using the Flutter framework and had two dashboard types: the daily sleep stage dashboard and the overall sleep stage dashboard, as presented in Fig. 10 and 11. The dashboard has two types of user access: patient and health practitioner.
Daily sleep quality and sleep stage dashboards show sleep quality, sleep stage percentage, and sleep metrics according to the applied date or time filter. The sleep stages were presented using a graph and several colors to identify each stage, and the sleep metrics consisted of awake duration, deep sleep, light sleep, REM, total sleep, wake time, time to sleep, sleep quality, and sleep efficiency.
The overall quality and sleep stage dashboards contained information about overall patient sleep quality displayed in bar charts with sleep quality as the y-axis and day as the x-axis. The display of all data depended on the provided start and end date filters. Sleep metrics showing the duration of awake, deep sleep, light sleep, REM, and total sleep, as well as time to sleep, wake time, sleep quality, and sleep efficiency were also shown.

V. RESULTS AND DISCUSSION
To evaluate the performance of the proposed IoT platform using microservices, event-driven, and the integration of WELM with PSO, four measurements were performed on a single machine with four CPUs equipped with 15 GB RAM and a clock rate of 2 GHz. The evaluations were performed as follows: 1) The first evaluation is related to the sensor gateway throughput and response time by measuring the number of transactions that the system can handle within a certain period. The number of transactions or requests per second was obtained for throughput evaluation. The duration of transaction or request being handled by a system was denoted as the response time, in which the measurement was started from the request sent to the server until the response was received [28]. A simulator streamed from the MIT-BIH database, was deployed to simulate the sensor data. A comparison to monolith and microservices architecture was made without event-driven or directly to the database with one and two replica applications. 2) RAM or memory usage evaluation of the proposed architectures was conducted and compared to monolith and microservices architecture with no event-driven architecture, or directly to the database using seven replica applications. 3) Execution time was evaluated for both the SQQS and SSCS. The speed of data processing from the sensor and the calculation of sleep quality data were determined. 4) Finally, the combined WELM and PSO algorithms for the imbalanced dataset were evaluated and compared to the previous method using the following metrics: model training and testing accuracy, sensitivity, specificity, and AUC. For the classification data, the annotations from the MIT-BIH database were used as a comparison.
A. THE EVALUATION OF THROUGHPUT AND RESPONSE TIME Fig. 12 shows a comparison of the evaluated architectures. For testing purposes, 20000 requests were made using the Apache Jmeter [29]. The microservices and eventdriven (McsED) architecture were compared to microservices without an event-driven architecture or directly to the database (McsDB) [29], as well as monolith architecture (MnlDB) [4], [5] with one and two service replicas. In summary, three architectures with two types of service replicas yielded six types of architecture. Table 2, Fig. 13, and Fig. 14 present comparisons of throughput and response times. The proposed system  [3], (d) 2McsDB [3], (e) 1MnlDB [4], [5], (f) 2MnlDB [4], [5]. exhibited the best performance for one and two replicas. Using one replica, the proposed architecture could process 803 sensor data with a response time of 253.34 ms. On two replicas, 1508 transactions were achieved every second with a response time of 68.8 ms.
Compared to the monolith architecture, which was directly connected to the database (MnlDB), the throughput was  increased by 92.59%, and the response time was decreased by 75.48% for two replicas owing to changes in microservices and event-driven architecture (McsED). The message broker implementation also increased the throughput by 34.76% and decreased the response time by 55.85% for two replicas compared to microservices without an event-driven architecture (McsDB). The proposed architecture improved the throughput and response time because the gateway sensor services were separated from other functions. Hence, transactions in the database were not required and they became more focused on performing tasks. Asynchronous data storage processing is possible using message broker, which is handled by the sensor data persister service. A lower performance was exhibited in the microservices without event-driven architecture (McsDB) because the sensor gateway required receiving and storing data in the database. The worst performance was shown in the monolith architecture (MnlDB) because of its requirement to provide all sleep quality monitoring functions in one large application. Fig. 15 shows RAM or resource memory usage per architecture for up to 7 replicas of sensor-gateway replication. Equation (3) was used to calculate v, which increases the rate in memory consumption per instance replication, where:

B. THE COMPARISON OF MEMORY USAGE
The most efficient memory usage was observed in the monolith architecture (MnlDB). In contrast, the highest memory consumption (2898 MB) was achieved in the proposed architecture (McsED).
The lowest memory usage for 2 to 4 replicas was achieved using McsDB. When the replica was further increased, the lowest memory consumption was obtained by the proposed architecture at 372 MB on average per added replica (v), compared to the microservices-database (McsDB) architecture and monolith architecture (MnlDB) at 592.5 MB and 1430.67 MB, respectively. Table 3 compares the rates of increase in memory usage per instance replication for the seven replicas. The microservices architecture provided low memory usage in the proposed method, in which the replication of the required services was enabled, namely, the sensor gateway. Sensor gateway replication cannot be performed separately in a single-entity application, such as a monolith architecture (MnlDB). Further reduction was made possible using eventdriven architecture, which results in reducing the additional RAM resource usage for connecting to the database. The addition of a gateway sensor replica (DB) in the McsDB architecture increases the database memory usage owing to the direct connection of the gateway sensor to the database, thus requiring more allocated memory.

C. THE EVALUATION OF SSCS AND SQQS EXECUTION TIME
After a patient's ECG data were fully collected for one day, the execution times of the SSCS and SQQS were evaluated.   16 shows the data flow of the ECG data for sleep quality processing. The slp41 file, which has 23400 ECG data (6 h 30 min long), was used as the ECG sample data, and the evaluation was performed 50 times.
The proposed architecture (McsED) consists of six steps to convert ECG data into sleep quality data. The first step was database reading using SSCS scheduler. Second, the ECG data in the sleep stage were classified using the SSCS. Third, the ''sleepStageReady'' event was published to the message broker by the SSCS. Fourth, the SSQS detected the ''sleep-StageReady'' event. Fifth, the sleep stage was converted into sleep quality using the SQQS. Finally, the sleep quality data were stored in the database.
The processes of the microservices database architecture (McsDB) and proposed architecture (McsED) were similar except in the third and fourth steps, which were converted into one step. This step was the SSCS call to the SQQS API, triggering sleep quality quantification instead of sending an event.
In contrast to McsDB and McsED, the monolith-database architectures (MnlDB) only contained three steps. First, the SSCS scheduler detected that the ECG data were stored in the database. Second, SSCS and SQQS performed the sleep classification process and sleep quality quantification. Third, the sleep quality data were stored in the database. Table 4 summarizes the average execution time comparison between WELM-PSO and ELM-PSO for each MIT-BIH record. The average execution time for the proposed architecture (McsED) was 5455 ms. In other words, the sleep quality data would be accessible to patients within ±5.5 ms after ECG data was collected. In comparison, the VOLUME 10, 2022 average execution time of microservices database (McsDB) and monolith database architecture (MnlDB) was 5028.7 ms and 4511.32 ms. The fastest processing time was achieved by using MnlDB as compared to other architectures because the processing in MnlDB was done in 1 source code. Hence, a remote function of the call procedure for other services is not necessary. Compared to the monolith and microservicesdatabase architecture, the proposed architecture was slower by 17.3% and 7.81%, respectively, because the amount of time to send and receive events between services was small.

D. PERFORMANCE OF PROPOSED WELM AND PSO ALGORITHM
The combined WELM and PSO algorithm was tested for 3 classes such as awake, NREM, REM, and 4 classes like awake, light sleep, deep sleep, and REM classification.
By extracting ECG data, there were 18 features obtained from the MIT-BIH polysomnographic database. The 'strongest' features that affected the result were determined using the PSO algorithm, while testing accuracy for fitness values was using the WELM algorithm. More information about feature selection and assessment can be found in previous research published as conference proceedings [19].
The accuracy results using WELM and PSO for the three classes was 78.78% and four classes was 73.09%, respectively. Meanwhile, 10 features highly influenced the accuracy results are 1) AVNN, 2) RMSSD, 3) SDNN, 4) pNN50, 5) SDSD, 6) HRV Triangular Index, 7) SD1, 8) area of ellipse, 9) TP, 10) LF-HF ratio. The results of the testing accuracy for each subject file in the MIT-BIH polysomnographic database are shown in Table 5. WELM as a substitute for ELM in the work of Lesmana et al. [15] increased the testing accuracy by 1.76% for three classes and 1.57% for four classes.
The results proved that the theory by Zong et al. [18] provided different C values by using matrix W , which gave a larger and smaller C value for the minority and majority class, respectively. The reason for the utilization of matrix W was to provide single C values for the whole equation, either large or small, while poor performance or poor generalization still occurred in the minority classes [18]. Tables 6 and 7 provide performance comparisons for three and four classes of related works and the combined WELM and PSO algorithms in this study. Compared to previous works [15]- [17], the combination of WELM and PSO in this study resulted in better performance in terms of accuracy and number of features for three and four classes.    To enhance the evaluation of the WELM-PSO combination, the sensitivity, specificity, AUC of the model from the ROC curves were also calculated. The highest results of the 18 samples for three classes and four classes are shown in Table 8, while the ROC curves for three and four classes are shown in Fig. 17 and 18.
The AUC ranges from 0.5 to 1. According to Khouli et al. [30], a classification model can be considered excellent if the AUC value ranges from 0.9 to 1. Our study  has the highest AUC values of 0.89 for both the three and four classes classification, which can be considered acceptable.

VI. CONCLUSION
This paper presents a study on IoT architecture for sleep quality monitoring and a combination of WELM with PSO for sleep stage classification. The entire system consists of two main concepts: event-driven and micro-services in the IoT platform, which then splits again into five micro-services: 1) sensor gateway, 2) sensor data persister, 3) sleep stage classification, 4) sleep quality quantification, and 5) application gateway. The communication between these services was triggered by events in an asynchronous manner between the message broker and services.
The processing time of 803 ECG requests per second was achieved using a single replica of the proposed system with a response time of 253.34 ms, whereas 1508 requests per second were also obtained using two replicas with a response time of 68.8 ms. Initially, the proposed system consumed the highest resources. As the number of replicas increased, the memory consumption has the lowest increase when compared to other systems since microservices have independently separated services. The system used 372 MB per replica for the sensor gateway replication in the average memory consumption per instance replication. Testing accuracies of 78.78% and 73.09% were obtained from the WELM-PSO algorithm, which were higher than other studies for three and four classes. In addition, the AUC of the proposed model was also calculated, and the highest result reached both 0.89 for the three and four class classification.
Despite these advantages, the data processing from raw ECG data into sleep quality data using the microservices and event-driven architecture was 7.81% and 17.3% slower than the other architectures, respectively, owing to the eventdriven communication system. However, the data flow in the proposed architecture can be improved by adding sensor transmission protocol and event compression. For future work, additional features obtained from other sensors may improve the accuracy of sleep stage classification, such as respiration sensors or actimetry. Moreover, the suggestion from the reviewer about using the sleep microstructure over the sleep macrostructure to assess sleep quality is also considered for further research.