Project Report2
Project Report2
A PROJECT REPORT
Submitted by
YAJNESH K (311622104059)
TARUN JAIN (311622104052)
SOUMYA RANJAN (311622104051)
of
BACHELOR OF ENGINEERING
in
COMPUTER SCIENCE AND ENGINEERING
1
ANNA UNIVERSITY: CHENNAI 600 025
BONAFIDE CERTIFICATE
SIGNATURE SIGNATURE
supervision.
2
ACKNOWLEDGEMENT
We thank our Principal, Dr. T. Sasikala, for her valuable suggestions and
guidance for the development and completion of this project.
Finally, we thank all the Teaching and Non-Teaching Staff members of our
Department who helped us to complete our project.
Above all we thank the Almighty, our parents and siblings for their constant
support and encouragement for completing this project.
3
MISRIMAL NAVAJEE MUNOTH JAIN ENGINEERING
COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND
ENGINEERING
• VISION
• MISSION
4
ABSTRACT
inherently reactive in nature — they detect issues only after failures have
already occurred, leaving little room for preventive action. This project
machine learning engine that learns the normal operational behavior of APIs
from historical log data, enabling it to detect deviations even in the case of
and resource scaling actions to improve system reliability and reduce overall
5
TABLE OF CONTENTS
CHAPTER
TITLE PAGE NO
NO
ABSTRACT v
LIST OF FIGURES viii
LIST OF ABBREVIATIONS viii
1. INTRODUCTION 1
1.1 MICROSERVICES AND API SYSTEMS 1
1.2 LOG-BASED MONITORING 2
MACHINE LEARNING FOR ANOMALY
1.3 3
DETECTION
1.4 AIOPS AND SELF-HEALING SYSTEMS 4
2. LITERATURE SURVEY 5
3. SYSTEM OVERVIEW 9
3.1 EXISTING SYSTEM 9
3.1.1 Overview 9
3.1.2 Drawback 9
3.2 PROPOSED SYSTEM 10
3.2.1 Overview 10
3.2.2 Advantages 10
3.3 REQUIREMENT ANALYSIS 11
3.3.1 Software Requirements 11
3.3.2 Hardware Requirements 11
3.4 TECHNOLOGIES USED 12
3.4.1 Java and Spring Boot 12
3.4.2 Python and scikit-learn 12
3.4.3 Isolation Forest Algorithm 13
3.4.4 PostgreSQL 13
3.4.5 IntelliJ IDEA and PyCharm 14
4. SYSTEM DESIGN 15
4.1 SYSTEM ARCHITECTURE 15
6
4.2 FUNCTIONAL ARCHITECTURE 16
4.3 UML USE CASE DIAGRAM 17
5. IMPLEMENTATION 18
5.1 MODULES 18
5.1.1 Backend API Execution and Log Generation 18
5.1.2 Log Acquisition and Streaming 19
5.1.3 Log Parsing and Feature Extraction 19
5.1.4 Data Preprocessing and Normalization 20
5.1.5 Machine Learning-Based Anomaly Detection 20
5.1.6 Health Assessment and Risk Classification 21
5.1.7 Monitoring Dashboard and Visualization 21
6. RESULTS 22
6.1 RESULT 22
7. SYSTEM TESTING 23
7.1 TESTING OBJECTIVES 23
7.2 TYPES OF TESTS 23
7.2.1 Unit Test Cases 24
7.2.2 Functional Test Cases 25
7.2.3 Integration Test Cases 26
8. CONCLUSION AND FUTURE ENHANCEMENT 27
8.1 CONCLUSION 27
8.2 FUTURE ENHANCEMENT 28
APPENDICES – CODE SNIPPET 29
APPENDICES – SCREENSHOT
REFERENCES
7
LIST OF FIGURES
LIST OF ABBREVIATIONS
ABBREVIATION EXPANSION
API APPLICATION PROGRAMMING INTERFACE
ML MACHINE LEARNING
AIOps ARTIFICIAL INTELLIGENCE FOR IT OPERATIONS
HTTP HYPERTEXT TRANSFER PROTOCOL
SRE SITE RELIABILITY ENGINEER
REST REPRESENTATIONAL STATE TRANSFER
MTTR MEAN TIME TO REPAIR
NLP NATURAL LANGUAGE PROCESSING
BIDIRECTIONAL ENCODER REPRESENTATIONS
BERT
FROM TRANSFORMERS
RCA ROOT CAUSE ANALYSIS
CPU CENTRAL PROCESSING UNIT
GPU GRAPHICS PROCESSING UNIT
IDE INTEGRATED DEVELOPMENT ENVIRONMENT
DB DATABASE
IoT INTERNET OF THINGS
8
CHAPTER 1
INTRODUCTION
1
challenge lies in doing so at scale, in real time, and with sufficient
intelligence to detect problems before they manifest as user-facing failures.
2
1.3 MACHINE LEARNING FOR ANOMALY DETECTION
3
1.4 AIOPS AND SELF-HEALING SYSTEMS
4
CHAPTER 2
LITERATURE SURVEY
Guangba Yu, Pengfei Chen, et al. [1] presented the Nezha framework
for interpretable, fine-grained root cause analysis of microservice failures
using multi-modal observability data. The paper's core contribution is the
integration of system metrics with log pattern data to diagnose not merely
that a failure has occurred, but precisely where and why it originated. The
framework demonstrates that combining logs and metrics provides
substantially more diagnostic accuracy than either modality alone, and that
human-interpretable results are as operationally important as detection
accuracy itself. The system achieves high precision in identifying root causes
of system failures and is particularly effective in large-scale, complex
5
microservice environments. However, the approach has notable limitations:
it requires high-quality, well-synchronized logs and metrics to function
correctly, and processing multi-modal data in real time is computationally
intensive. Additionally, the method may struggle to generalize to entirely
new failure types that do not correspond to any patterns present in the
training corpus.
6
observability data on which performance depends, and the configuration
overhead involved in integrating end-to-end monitoring across diverse and
heterogeneous microservice deployments.
CHAPTER 3
SYSTEM OVERVIEW
3.1.1 Overview
Contemporary backend systems make use of monitoring and
observability tools to track the behavior of APIs and services in production.
These tools observe key performance indicators such as request latency, error
rates, and throughput, and apply predefined rules and thresholds to determine
when the system has entered an unacceptable state. When a metric breaches
its configured limit — for example, when API latency exceeds a fixed
threshold or when the count of server-side error responses surpasses a
defined value — the monitoring system generates an alert and notifies the
responsible operations team. Engineers then manually investigate the alert,
examine the raw logs, and attempt to diagnose the root cause of the issue.
3.1.2 Drawback
▪ Problems are detected only after they have fully manifested, leaving
no opportunity for preventive intervention.
▪ The threshold-based approach cannot detect gradual or novel forms of
abnormal behavior that do not correspond to any explicitly configured
rule.
▪ Static thresholds generate excessive false positive alerts when traffic
patterns are inherently variable, leading to alert fatigue among
operations teams.
7
▪ Engineers must manually analyze raw log data to understand the
nature of each issue, a process that is both time-consuming and
dependent on individual expertise.
▪ The system provides no guidance on recommended corrective actions,
requiring engineers to determine an appropriate response
independently for each incident.
3.2.1 Overview
The proposed system is a log-based AIOps prototype inspired by
research on microservice anomaly detection. It ingests API and system logs
in real time, extracts meaningful statistical features using time-window
aggregation, and applies an unsupervised machine learning model to learn
normal API behavior from historical data. The model continuously scores
incoming log-derived feature vectors and identifies deviations from the
learned baseline, including anomaly types that have never previously been
observed. When an anomaly is detected, the system classifies its severity,
generates a human-readable health assessment, and surfaces recovery
recommendations — such as retry mechanisms, circuit breaking, or resource
scaling — through a real-time monitoring dashboard.
3.2.2 Advantages
▪ Detects abnormal behavior earlier than conventional threshold-based
alert systems, enabling preventive action.
▪ Reduces alert noise by focusing on statistically unusual patterns rather
than static rule violations.
8
▪ Assists engineers in responding faster by pairing each detected
anomaly with a relevant recovery recommendation.
▪ Applicable broadly to any API-based backend system that generates
structured operational logs.
▪ Employs an unsupervised learning approach that requires no labeled
anomaly data for training.
3.3.1 Software Requirements
The software requirements give a detailed description of the system and
all its features.
9
3.3.2 Hardware Requirements
The hardware requirements may serve as the basis for a contract for the
implementation of the system and should therefore be a complete and precise
description of the technical requirements.
10
libraries for numerical computation, data manipulation, and model training.
The scikit-learn library provides efficient, well-documented implementations
of a wide range of machine learning algorithms, including the Isolation
Forest model used as the core anomaly detector in this project. Pandas and
NumPy are used for data manipulation and feature engineering tasks,
enabling the efficient transformation of raw log entries into the structured
numerical feature vectors that the ML model requires.
3.4.4 PostgreSQL
PostgreSQL is a powerful, open-source relational database
management system that offers full ACID compliance, advanced indexing,
and robust support for complex queries. In this system, PostgreSQL serves
as the primary structured data store for processed feature metrics, anomaly
detection results, health assessment scores, and risk classification labels. Its
reliability and widespread adoption in production environments make it an
11
appropriate choice for storing the persistent state of the monitoring system
and supporting the dashboard's historical trend visualization capabilities.
12
CHAPTER 4
SYSTEM DESIGN
13
These logs are continuously collected by a log acquisition layer and
forwarded to the feature extraction pipeline, where raw log entries are
transformed into structured numerical feature vectors using
time-window-based aggregation. The processed features are passed to the
Python-based machine learning engine, where an Isolation Forest model
scores each feature vector according to its deviation from the learned normal
baseline. The resulting anomaly scores are interpreted by a health assessment
module, which classifies the current system state and generates recovery
recommendations. All outputs are persisted to a PostgreSQL database and
surfaced through a real-time monitoring dashboard for operator visibility.
14
Figure 4.1 Function Architecture
These features are normalized and scaled before being submitted to the
anomaly detection engine, where the trained Isolation Forest model produces
a continuous anomaly score. The scoring output feeds into the risk
classification layer, which applies severity thresholds to produce categorical
health labels. Finally, the dashboard layer retrieves the classified results and
presents them visually alongside trend charts and recommended recovery
actions.
The UML Use Case Diagram represents the interactions between the
system's actors and the functional capabilities it exposes.
15
Figure 4.3 UML Use Case Diagram
16
17
18
CHAPTER 5
IMPLEMENTATION
5.1 MODULES
19
Outputs from this module include API access logs, error logs, and latency
logs.
20
cause the anomaly detection model to develop a distorted view of system
behavior.
Once buffered and validated, log entries are forwarded to the feature
extraction pipeline for further processing.
21
derive the final feature set. The extracted features include mean latency per
time window, maximum latency per time window, error rate calculated as the
proportion of 4xx and 5xx responses to total requests, total request count per
window, and timeout occurrence count.
22
versus error rates expressed as small decimal fractions — which can
adversely affect the performance of distance-based anomaly detection
algorithms. The preprocessing pipeline addresses this by applying standard
feature scaling techniques that bring all feature dimensions into a
comparable numerical range.
23
5.1.5 Machine Learning-Based Anomaly Detection
The fifth module constitutes the core intelligence layer of the system.
The machine learning engine trains an Isolation Forest model on a corpus of
historical log-derived feature vectors representing the system's normal
operational behavior. The trained model learns to distinguish the compact,
densely distributed region of the feature space that corresponds to normal
API behavior from the sparser, more distant regions that may indicate
anomalous conditions. Once trained, the model is applied continuously to
incoming feature vectors, producing a real-valued anomaly score for each
time window. Feature vectors that fall in regions of the feature space that the
model has not previously observed receive high anomaly scores,
24
while vectors consistent with normal operation receive scores close to zero.
An optional Autoencoder neural network extension is also considered for
capturing more complex, non-linear behavioral patterns in the feature space.
25
system state to one of three health categories: Healthy, indicating that all
metrics are within normal ranges; Warning,indicating that anomalous
behavior has been detected but the system is still operational; or Critical,
indicating a high-confidence detection of severe abnormal behavior with
significant risk of imminent service disruption. For each classified state, the
module generates an associated recovery recommendation,selecting from a
catalogue of predefined actions including increased retry intervals, activation
of circuit breaker mechanisms, and horizontal resource scaling.
26
windows in which anomalies have been detected, displays the current system
health classification with an associated risk level indicator, and presents the
recommended recovery action for any active [Link] dashboard is
designed to support rapid incident response by surfacing the most
operationally relevant information clearly and without unnecessary
complexity. It also supports retrospective analysis by providing access to
historical anomaly records and trend data stored in the PostgreSQL database.
27
CHAPTER 6
RESULTS
6.1 RESULT
28
suggestions for each classified incident. The end-to-end pipeline from log
ingestion through to dashboard visualization operated within acceptable
latency bounds, confirming the viability of the architecture for near-real-time
monitoring applications.
29
CHAPTER 7
SYSTEM TESTING
30
project the unit testing validates the program logic of all modules across the
anomaly detection pipeline.
31
Valid Input: Structured API log files (JSON or plain text format), live log
streams from Spring Boot backend.
32
In this project the integration testing verifies correct data flow across all
seven modules from log ingestion through to dashboard visualization.
Input: Complete API log dataset from LO2 benchmark; live log stream from
running Spring Boot service.
Expected
Test ID Integration Scope Scenario Result
Outcome
Features
Log Acquisition to Continuous log
IT-01 extracted Pass
Feature Extraction stream ingested
without data loss
Anomaly scores
Feature Extraction Feature vectors
IT-02 returned for all Pass
to ML Engine submitted to model
vectors
Scores forwarded All scores
ML Engine to
IT-03 to classification correctly Pass
Health Classifier
layer classified
Dashboard
Classifier to Results forwarded
IT-04 updates in real Pass
Dashboard to visualization
time
LO2 benchmark Known anomaly
IT-05 Full Pipeline dataset processed periods correctly Pass
end-to-end identified
33
CHAPTER 8
8.1 CONCLUSION
System metrics were collected from the LO2 benchmark dataset and
validated against live Podinfo microservice telemetry, ensuring both research
validity and practical relevance. Proper feature engineering — specifically
the conversion of cumulative counters into rate-based metrics — was found
to be essential for reliable model performance and significantly reduced the
incidence of false anomaly detections. The trained ML model was integrated
with a Java Spring Boot backend through a well-defined REST API
interface, enabling a scalable and modular system architecture. Anomaly
detection results were persistently stored and surfaced through a monitoring
dashboard that supports both real-time incident response and retrospective
trend analysis.
34
The project's outcomes not only validate the feasibility of machine
learning-driven anomaly detection as a complement to traditional rule-based
API monitoring, but also underscore the potential for transformative
advancements in intelligent, self-healing API infrastructure. This endeavor
serves as a testament to the capabilities of modern AIOps engineering and
paves the way for future developments in predictive monitoring
technologies, promising a future of more reliable, efficient, and autonomous
API systems.
35
Log Semantic Analysis with NLP: Incorporate natural language processing
techniques, inspired by approaches such as LogBERT, to extract semantic
features from the textual content of error log messages, enabling the system
to detect anomalies that manifest primarily in log message patterns rather
than in numerical performance metrics.
36
8.3 APPENDICES – CODE SNIPPET
A.1 Isolation Forest Model Training - train_model.py
The following snippet shows the core model training logic. The full training
script includes data loading, feature engineering, cross-validation, and result
visualisation.
The following snippet shows the core prediction logic. The full service
includes batch prediction, health checks, model metadata endpoints, and
CORS middleware.
@[Link]("/predict", response_model=AnomalyPrediction)
async def predict(metrics: MetricFeatures):
features_df = prepare_features([Link])
features_scaled = model_manager.[Link](features_df)
prediction = model_manager.[Link](features_scaled)[0]
37
anomaly_score =
model_manager.model.score_samples(features_scaled)[0]
is_anomaly = prediction == -1
confidence = determine_confidence(anomaly_score)
return AnomalyPrediction(
timestamp = [Link]().isoformat(),
is_anomaly = is_anomaly,
anomaly_score = float(anomaly_score),
confidence = confidence,
recommendation= generate_recommendation(anomaly_score,
is_anomaly))
The following snippet shows the pattern-matching decision logic. The full
service includes recovery tracking, consecutive clean cycle counting, and
RESUME recommendation.
38
"Abnormal metric combination",
"Temporarily stop traffic and perform root cause analysis.");
}
// Pattern 4 — Moderate anomaly
return build("WARNING", "RETRY",
"Transient deviation",
"Retry requests with exponential backoff and monitor closely.");
}
The following snippet shows how raw Prometheus counters are converted
to rate-based features. The full script includes data merging, outlier removal,
and train/test split.
def compute_features(df):
df = df.sort_values('timestamp')
dt = df['timestamp'].diff().dt.total_seconds().fillna(5)
def rate(col):
return df[col].diff().fillna(0) / [Link](0, 5)
features = [Link]()
features['http_requests_total_rate_per_sec'] =
rate('http_requests_total').clip(lower=0)
features['http_request_duration_seconds_sum_rate'] =
rate('http_request_duration_seconds_sum').clip(lower=0)
features['avg_request_duration_sec'] =(
features['http_request_duration_seconds_sum_rate'] /
rate('http_request_duration_seconds_count').clip(lower=0.001)
)
features['go_goroutines'] = df['go_goroutines']
features['process_open_fds'] = df['process_open_fds']
return [Link]()
39
A.5 Dashboard — Prometheus Metric Parser (live_dashboardX.html)
The following snippet shows how the browser parses raw Prometheus text
into numerical values. The full dashboard includes chart rendering,
simulation ramp logic, 3-colour state machine, and recovery tracking.
function parseMetrics(text) {
const get = name => {
const m = [Link](
new RegExp('^' + name + '(?:{[^}]*})? ([\\d.e+\\-]+)', 'm')
);
return m ? parseFloat(m[1]) : 0;
};
return {
go_goroutines: get('go_goroutines'),
go_memstats_alloc_bytes: get('go_memstats_alloc_bytes'),
go_memstats_heap_inuse_bytes:
get('go_memstats_heap_inuse_bytes'),
process_open_fds: get('process_open_fds'),
http_requests_total: get('http_requests_total'),
http_request_duration_seconds_sum:
get('http_request_duration_seconds_sum'),
http_request_duration_seconds_count:
get('http_request_duration_seconds_count'),
process_cpu_seconds_total: get('process_cpu_seconds_total'),
};
}
40
8.3 APPENDICES – SYSTEM SCREENSHOT
The dashboard in its normal operating state. The status banner displays
SYSTEM NORMAL in green with a checkmark icon. The anomaly score
panel shows a score around -0.38, confidence LOW, and action Continue
Monitoring. Goroutines are at baseline (9–13 threads), memory allocation is
stable at approximately 21 MB, and the goroutine chart shows a flat blue
line. The real-time analysis log confirms consecutive normal readings with
varying goroutine and FD values, confirming the system is operating within
learned normal parameters.
41
The dashboard transitioning from normal to anomaly during stress injection.
The status banner has turned yellow and displays ELEVATED RISK. The
anomaly score has drifted to approximately -0.45, approaching the -0.50
detection threshold. The goroutine chart shows an upward curve beginning
around 60–80 threads. The analysis log shows ELEVATED entries with ramp
percentage, indicating the system has detected metric drift but not yet
confirmed a full anomaly. This intermediate state gives operators early
warning before the threshold is crossed.
The dashboard in full anomaly state triggered by the stress load pattern. The
banner displays ANOMALY DETECTED in red with an exclamation icon.
The anomaly score reads -0.75, confidence HIGH. The action field shows
Isolate & Stop Inbound Traffic. The goroutine card shows 800+ threads,
open FDs have spiked correspondingly. The analysis log shows CRITICAL
entries with trigger pattern Goroutine explosion + FD exhaustion and
operator guidance to enable circuit breaker and investigate upstream traffic
source. The goroutine chart shows a sharp exponential climb in red.
42
REFERENCES
43