Security Operations Platform
Project Summary (6W Pitch Framework)
- Who (Target Customers and Core Roles): Designed for security operations teams at large enterprises, with an AI full-stack engineer leading the core architecture design and business-domain development.
- What (Core Product and Problems Addressed): An integrated enterprise-grade security operations management platform that addresses delayed processing of high-volume security alerts and fragmented risk management. It provides unified capabilities for cybersecurity monitoring, asset management, vulnerability remediation, and AI-powered intelligent analysis.
- Why (Core Differentiators and Competitive Advantages): Implements a three-tier data delivery strategy combining scheduled tasks, Redis caching, and real-time aggregation with cache backfilling on misses, reducing core API response times to under 50 ms. It enables a fully automated closed loop from risk identification to protection response.
- Where (Use Cases and Deployment Environments): Supports multi-scenario enterprise security operations, firewall integration, and domain security monitoring. It also provides Docker-based container orchestration for isolated multi-environment deployments and dynamic switching between data sources.
- When (Timeliness and Real-Time Capabilities): Processes more than 100,000 raw alerts from network security devices in real time each day. It supports five-minute scheduled aggregation and cache refresh cycles, while completing full-table aggregation across more than 150 tables containing tens of thousands of records within three seconds.
- How (Technical Approach and Delivery Model): Uses a microservices architecture to separate business modules and reuse shared capability libraries. It establishes a real-time analysis and automated device-response pipeline powered by Kafka, InfluxDB, a rules engine.
Business
- AI: Integrates AI Agents to perform intelligent attack-path analysis, three-dimensional risk assessment across systems, assets, and vulnerabilities, and automated generation of remediation recommendations.
- Automation: Provides a public IP blacklist analysis API that enables firewall devices to retrieve data, creating a fully automated process from risk identification to protection response.
- Concurrency: Supports real-time processing across more than 150 business tables and over 100,000 alerts per day. Core monitoring API response times were reduced from over two seconds to under 50 ms, while Redis-only APIs support more than 500 queries per second.
- Availability: Automatically falls back to database queries when the cache becomes unavailable, ensuring 99.9% system availability.
- Localization: Enables seamless switching between the Dameng database and the PostgreSQL.
- Efficiency: Improves development and delivery efficiency through independent microservice iteration and reuse of shared capability libraries.
Tech Stack
- Backend: Spring Boot 3.2.6
- Frontend: Vue 3
- Database: InfluxDB
- Cache: Redis
- Middleware: Kafka
- Containerization: Docker
This guide builds a local development environment that separates a security operations platform into independent business modules while reusing shared capability libraries. The implementation uses Java 17, Spring Boot 3.2.6, Apache Maven, PostgreSQL, Redis, Kafka, and Docker Compose.
The sample contains an alert service, an asset service, and a response service. Each service owns one business responsibility and exposes its own contract. A shared internal library provides event envelopes, correlation identifiers, tenant context, standard API errors, and common logging behavior. The services communicate synchronously through HTTP only where an immediate answer is required and asynchronously through Kafka for business events.
The local design demonstrates practical service boundaries without creating an excessive number of processes. It avoids a shared application database, prevents direct cross-service table access, and makes shared capabilities reusable without placing domain rules inside the common library.
This guide is limited to local development. It does not include production acceptance criteria or production acceptance tests.
Step 1: Prepare the Local Development Environment
Install Java Development Kit 17, Apache Maven 3.9 or later, Docker Desktop or Docker Engine with Docker Compose v2, Git, curl, and an IDE such as IntelliJ IDEA or Visual Studio Code.
Confirm the tools:
java -version
mvn -version
docker --version
docker compose version
git --version
curl --version
Create the parent project and module directories:
mkdir security-platform-microservices
cd security-platform-microservices
mkdir -p shared-capabilities/src/main/java/com/example/security/shared/context
mkdir -p shared-capabilities/src/main/java/com/example/security/shared/event
mkdir -p shared-capabilities/src/main/java/com/example/security/shared/web
mkdir -p alert-service/src/main/java/com/example/security/alert/controller
mkdir -p alert-service/src/main/java/com/example/security/alert/domain
mkdir -p alert-service/src/main/java/com/example/security/alert/repository
mkdir -p alert-service/src/main/java/com/example/security/alert/service
mkdir -p alert-service/src/main/resources
mkdir -p asset-service/src/main/java/com/example/security/asset/controller
mkdir -p asset-service/src/main/java/com/example/security/asset/domain
mkdir -p asset-service/src/main/java/com/example/security/asset/repository
mkdir -p asset-service/src/main/java/com/example/security/asset/service
mkdir -p asset-service/src/main/resources
mkdir -p response-service/src/main/java/com/example/security/response/controller
mkdir -p response-service/src/main/java/com/example/security/response/domain
mkdir -p response-service/src/main/java/com/example/security/response/repository
mkdir -p response-service/src/main/java/com/example/security/response/service
mkdir -p response-service/src/main/resources
The parent project will build all modules in one Maven reactor while each service remains independently executable. This arrangement is convenient on a local machine and does not require the services to share domain code or databases.
Step 2: Define the Business Boundaries
The alert service owns security-alert ingestion, alert status, severity, source data, and alert events. It does not own asset criticality or response execution.
The asset service owns asset identity, hostname, business criticality, owner information, and asset lookup. Other services consume its API rather than reading its database.
The response service owns response decisions and response records. It consumes alert events, obtains asset context through the asset service, applies its own containment policy, and stores the resulting decision.
The shared-capabilities module contains only technical behavior that must remain consistent across services. It contains correlation handling, tenant context, a standard event envelope, and a standard error response. It contains no alert, asset, vulnerability, or firewall business rules.
This separation is important. Reusing technical behavior reduces repeated engineering work. Reusing domain models across every service would couple independent business modules and recreate a distributed monolith.
Step 3: Create the Parent Maven Project
Create the root pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.6</version>
<relativePath/>
</parent>
<groupId>com.example.security</groupId>
<artifactId>security-platform-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>shared-capabilities</module>
<module>alert-service</module>
<module>asset-service</module>
<module>response-service</module>
</modules>
<properties>
<java.version>17</java.version>
<shared-capabilities.version>1.0.0-SNAPSHOT</shared-capabilities.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.example.security</groupId>
<artifactId>shared-capabilities</artifactId>
<version>${shared-capabilities.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
The parent controls compatible framework and shared-library versions. Each service still declares only the dependencies it uses.
Step 4: Build the Shared Capability Library
Create shared-capabilities/pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example.security</groupId>
<artifactId>security-platform-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>shared-capabilities</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
</project>
Create shared-capabilities/src/main/java/com/example/security/shared/context/RequestContext.java:
package com.example.security.shared.context;
public final class RequestContext {
private static final ThreadLocal<String> CORRELATION_ID = new ThreadLocal<>();
private static final ThreadLocal<String> TENANT_ID = new ThreadLocal<>();
private RequestContext() {
}
public static void set(String correlationId, String tenantId) {
CORRELATION_ID.set(correlationId);
TENANT_ID.set(tenantId);
}
public static String correlationId() {
return CORRELATION_ID.get();
}
public static String tenantId() {
return TENANT_ID.get();
}
public static void clear() {
CORRELATION_ID.remove();
TENANT_ID.remove();
}
}
Create shared-capabilities/src/main/java/com/example/security/shared/context/RequestContextFilter.java:
package com.example.security.shared.context;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.UUID;
public class RequestContextFilter extends OncePerRequestFilter {
public static final String CORRELATION_HEADER = "X-Correlation-Id";
public static final String TENANT_HEADER = "X-Tenant-Id";
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain
) throws ServletException, IOException {
String correlationId = valueOrDefault(
request.getHeader(CORRELATION_HEADER),
UUID.randomUUID().toString()
);
String tenantId = request.getHeader(TENANT_HEADER);
if (tenantId == null || tenantId.isBlank()) {
response.sendError(400, "Missing X-Tenant-Id header");
return;
}
try {
RequestContext.set(correlationId, tenantId);
MDC.put("correlationId", correlationId);
MDC.put("tenantId", tenantId);
response.setHeader(CORRELATION_HEADER, correlationId);
filterChain.doFilter(request, response);
} finally {
MDC.remove("correlationId");
MDC.remove("tenantId");
RequestContext.clear();
}
}
private String valueOrDefault(String value, String fallback) {
return value == null || value.isBlank() ? fallback : value;
}
}
Create shared-capabilities/src/main/java/com/example/security/shared/event/EventEnvelope.java:
package com.example.security.shared.event;
import java.time.Instant;
public record EventEnvelope<T>(
String eventId,
String eventType,
int schemaVersion,
String tenantId,
String correlationId,
String sourceService,
Instant occurredAt,
Instant publishedAt,
T payload
) {
}
Create shared-capabilities/src/main/java/com/example/security/shared/web/ApiError.java:
package com.example.security.shared.web;
import java.time.Instant;
public record ApiError(
String code,
String message,
String correlationId,
Instant timestamp
) {
}
Create shared-capabilities/src/main/java/com/example/security/shared/web/StandardExceptionHandler.java:
package com.example.security.shared.web;
import com.example.security.shared.context.RequestContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.time.Instant;
@RestControllerAdvice
public class StandardExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
ResponseEntity<ApiError> validation(MethodArgumentNotValidException ex) {
ApiError error = new ApiError(
"VALIDATION_ERROR",
ex.getBindingResult().getAllErrors().getFirst().getDefaultMessage(),
RequestContext.correlationId(),
Instant.now()
);
return ResponseEntity.badRequest().body(error);
}
@ExceptionHandler(IllegalArgumentException.class)
ResponseEntity<ApiError> badRequest(IllegalArgumentException ex) {
ApiError error = new ApiError(
"BAD_REQUEST",
ex.getMessage(),
RequestContext.correlationId(),
Instant.now()
);
return ResponseEntity.badRequest().body(error);
}
@ExceptionHandler(Exception.class)
ResponseEntity<ApiError> unexpected(Exception ex) {
ApiError error = new ApiError(
"INTERNAL_ERROR",
"The service could not complete the request",
RequestContext.correlationId(),
Instant.now()
);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}
The library packages consistent technical behavior. It does not import the alert, asset, or response modules. This one-way dependency rule keeps business modules independent.
Step 5: Start PostgreSQL, Redis, and Kafka Locally
Create compose.yaml in the project root:
services:
alert-db:
image: postgres:16-alpine
container_name: security-alert-db
environment:
POSTGRES_DB: alert_db
POSTGRES_USER: alert_user
POSTGRES_PASSWORD: alert_password
ports:
- "5433:5432"
volumes:
- alert_db_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U alert_user -d alert_db"]
interval: 5s
timeout: 3s
retries: 20
asset-db:
image: postgres:16-alpine
container_name: security-asset-db
environment:
POSTGRES_DB: asset_db
POSTGRES_USER: asset_user
POSTGRES_PASSWORD: asset_password
ports:
- "5434:5432"
volumes:
- asset_db_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U asset_user -d asset_db"]
interval: 5s
timeout: 3s
retries: 20
response-db:
image: postgres:16-alpine
container_name: security-response-db
environment:
POSTGRES_DB: response_db
POSTGRES_USER: response_user
POSTGRES_PASSWORD: response_password
ports:
- "5435:5432"
volumes:
- response_db_data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U response_user -d response_db"]
interval: 5s
timeout: 3s
retries: 20
redis:
image: redis:7.2-alpine
container_name: security-shared-redis
ports:
- "6379:6379"
command: ["redis-server", "--appendonly", "yes"]
volumes:
- redis_data:/data
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 5s
timeout: 3s
retries: 20
kafka:
image: bitnami/kafka:3.7
container_name: security-module-kafka
ports:
- "9092:9092"
environment:
KAFKA_CFG_NODE_ID: 1
KAFKA_CFG_PROCESS_ROLES: broker,controller
KAFKA_CFG_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093
KAFKA_CFG_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:PLAINTEXT,INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT
KAFKA_CFG_LISTENERS: INTERNAL://:29092,CONTROLLER://:9093,EXTERNAL://:9092
KAFKA_CFG_ADVERTISED_LISTENERS: INTERNAL://kafka:29092,EXTERNAL://localhost:9092
KAFKA_CFG_INTER_BROKER_LISTENER_NAME: INTERNAL
KAFKA_CFG_CONTROLLER_LISTENER_NAMES: CONTROLLER
KAFKA_CFG_AUTO_CREATE_TOPICS_ENABLE: "false"
ALLOW_PLAINTEXT_LISTENER: "yes"
volumes:
- kafka_data:/bitnami/kafka
healthcheck:
test: ["CMD-SHELL", "/opt/bitnami/kafka/bin/kafka-topics.sh --bootstrap-server localhost:9092 --list >/dev/null 2>&1"]
interval: 10s
timeout: 5s
retries: 20
kafka-init:
image: bitnami/kafka:3.7
depends_on:
kafka:
condition: service_healthy
entrypoint:
- /bin/bash
- -ec
- |
/opt/bitnami/kafka/bin/kafka-topics.sh --bootstrap-server kafka:29092 --create --if-not-exists --topic security.alerts.v1 --partitions 3 --replication-factor 1
/opt/bitnami/kafka/bin/kafka-topics.sh --bootstrap-server kafka:29092 --create --if-not-exists --topic security.responses.v1 --partitions 3 --replication-factor 1
volumes:
alert_db_data:
asset_db_data:
response_db_data:
redis_data:
kafka_data:
Each business service receives its own PostgreSQL database and credentials. This local separation makes accidental cross-service table access difficult and demonstrates data ownership clearly.
Start the infrastructure:
docker compose up -d
Check health:
docker compose ps
Confirm Kafka topics:
docker exec -it security-module-kafka \
/opt/bitnami/kafka/bin/kafka-topics.sh \
--bootstrap-server localhost:9092 \
--list
Step 6: Implement the Asset Service
Create asset-service/pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.example.security</groupId>
<artifactId>security-platform-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>asset-service</artifactId>
<dependencies>
<dependency>
<groupId>com.example.security</groupId>
<artifactId>shared-capabilities</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Create asset-service/src/main/java/com/example/security/asset/AssetServiceApplication.java:
package com.example.security.asset;
import com.example.security.shared.context.RequestContextFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
@SpringBootApplication
@Import(com.example.security.shared.web.StandardExceptionHandler.class)
public class AssetServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AssetServiceApplication.class, args);
}
@Bean
RequestContextFilter requestContextFilter() {
return new RequestContextFilter();
}
}
Create the asset entity in asset-service/src/main/java/com/example/security/asset/domain/Asset.java:
package com.example.security.asset.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
@Entity
@Table(name = "assets")
public class Asset {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String tenantId;
private String assetId;
private String hostname;
private String criticality;
private String ownerName;
protected Asset() {
}
public Asset(String tenantId, String assetId, String hostname, String criticality, String ownerName) {
this.tenantId = tenantId;
this.assetId = assetId;
this.hostname = hostname;
this.criticality = criticality;
this.ownerName = ownerName;
}
public Long getId() { return id; }
public String getTenantId() { return tenantId; }
public String getAssetId() { return assetId; }
public String getHostname() { return hostname; }
public String getCriticality() { return criticality; }
public String getOwnerName() { return ownerName; }
}
Create the repository:
package com.example.security.asset.repository;
import com.example.security.asset.domain.Asset;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface AssetRepository extends JpaRepository<Asset, Long> {
Optional<Asset> findByTenantIdAndAssetId(String tenantId, String assetId);
}
Create asset-service/src/main/java/com/example/security/asset/controller/AssetController.java:
package com.example.security.asset.controller;
import com.example.security.asset.domain.Asset;
import com.example.security.asset.repository.AssetRepository;
import com.example.security.shared.context.RequestContext;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/assets")
public class AssetController {
private final AssetRepository repository;
public AssetController(AssetRepository repository) {
this.repository = repository;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public Asset create(@RequestBody CreateAssetRequest request) {
return repository.save(new Asset(
RequestContext.tenantId(),
request.assetId(),
request.hostname(),
request.criticality(),
request.ownerName()
));
}
@GetMapping("/{assetId}")
public Asset get(@PathVariable String assetId) {
return repository.findByTenantIdAndAssetId(RequestContext.tenantId(), assetId)
.orElseThrow(() -> new IllegalArgumentException("Asset not found"));
}
public record CreateAssetRequest(
String assetId,
String hostname,
String criticality,
String ownerName
) {
}
}
Create asset-service/src/main/resources/application.yml:
server:
port: 8082
spring:
application:
name: asset-service
datasource:
url: jdbc:postgresql://localhost:5434/asset_db
username: asset_user
password: asset_password
jpa:
hibernate:
ddl-auto: update
open-in-view: false
management:
endpoints:
web:
exposure:
include: health,info,metrics
The asset service is authoritative for asset criticality. The response service will use its API instead of joining the asset database.
Step 7: Implement the Alert Service
Create alert-service/pom.xml with the same Spring Boot web, JPA, validation, PostgreSQL, actuator, and shared-capabilities dependencies as the asset service. Add Spring Kafka:
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
Create alert-service/src/main/java/com/example/security/alert/AlertServiceApplication.java:
package com.example.security.alert;
import com.example.security.shared.context.RequestContextFilter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
@SpringBootApplication
@Import(com.example.security.shared.web.StandardExceptionHandler.class)
public class AlertServiceApplication {
public static void main(String[] args) {
SpringApplication.run(AlertServiceApplication.class, args);
}
@Bean
RequestContextFilter requestContextFilter() {
return new RequestContextFilter();
}
}
Create the alert entity:
package com.example.security.alert.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.Instant;
@Entity
@Table(name = "security_alerts")
public class SecurityAlert {
@Id
private String alertId;
private String tenantId;
private String assetId;
private String sourceIp;
private String severity;
private String status;
private Instant detectedAt;
protected SecurityAlert() {
}
public SecurityAlert(
String alertId,
String tenantId,
String assetId,
String sourceIp,
String severity,
String status,
Instant detectedAt
) {
this.alertId = alertId;
this.tenantId = tenantId;
this.assetId = assetId;
this.sourceIp = sourceIp;
this.severity = severity;
this.status = status;
this.detectedAt = detectedAt;
}
public String getAlertId() { return alertId; }
public String getTenantId() { return tenantId; }
public String getAssetId() { return assetId; }
public String getSourceIp() { return sourceIp; }
public String getSeverity() { return severity; }
public String getStatus() { return status; }
public Instant getDetectedAt() { return detectedAt; }
}
Create the repository:
package com.example.security.alert.repository;
import com.example.security.alert.domain.SecurityAlert;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SecurityAlertRepository extends JpaRepository<SecurityAlert, String> {
}
Create the business event payload:
package com.example.security.alert.service;
import java.time.Instant;
public record AlertCreated(
String alertId,
String assetId,
String sourceIp,
String severity,
Instant detectedAt
) {
}
Create AlertApplicationService.java:
package com.example.security.alert.service;
import com.example.security.alert.domain.SecurityAlert;
import com.example.security.alert.repository.SecurityAlertRepository;
import com.example.security.shared.context.RequestContext;
import com.example.security.shared.event.EventEnvelope;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.UUID;
@Service
public class AlertApplicationService {
private final SecurityAlertRepository repository;
private final KafkaTemplate<String, Object> kafkaTemplate;
public AlertApplicationService(
SecurityAlertRepository repository,
KafkaTemplate<String, Object> kafkaTemplate
) {
this.repository = repository;
this.kafkaTemplate = kafkaTemplate;
}
@Transactional
public SecurityAlert create(CreateAlertCommand command) {
SecurityAlert alert = new SecurityAlert(
command.alertId(),
RequestContext.tenantId(),
command.assetId(),
command.sourceIp(),
command.severity().toUpperCase(),
"OPEN",
command.detectedAt()
);
repository.save(alert);
AlertCreated payload = new AlertCreated(
alert.getAlertId(),
alert.getAssetId(),
alert.getSourceIp(),
alert.getSeverity(),
alert.getDetectedAt()
);
EventEnvelope<AlertCreated> event = new EventEnvelope<>(
UUID.randomUUID().toString(),
"AlertCreated",
1,
RequestContext.tenantId(),
RequestContext.correlationId(),
"alert-service",
alert.getDetectedAt(),
Instant.now(),
payload
);
kafkaTemplate.send(
"security.alerts.v1",
RequestContext.tenantId() + ":" + alert.getAssetId(),
event
);
return alert;
}
public record CreateAlertCommand(
String alertId,
String assetId,
String sourceIp,
String severity,
Instant detectedAt
) {
}
}
Create AlertController.java:
package com.example.security.alert.controller;
import com.example.security.alert.domain.SecurityAlert;
import com.example.security.alert.service.AlertApplicationService;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/alerts")
public class AlertController {
private final AlertApplicationService service;
public AlertController(AlertApplicationService service) {
this.service = service;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public SecurityAlert create(
@RequestBody AlertApplicationService.CreateAlertCommand command
) {
return service.create(command);
}
}
Create alert-service/src/main/resources/application.yml:
server:
port: 8081
spring:
application:
name: alert-service
datasource:
url: jdbc:postgresql://localhost:5433/alert_db
username: alert_user
password: alert_password
jpa:
hibernate:
ddl-auto: update
open-in-view: false
kafka:
bootstrap-servers: localhost:9092
producer:
acks: all
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.springframework.kafka.support.serializer.JsonSerializer
properties:
enable.idempotence: true
management:
endpoints:
web:
exposure:
include: health,info,metrics
For a larger implementation, replace the direct database-write-then-Kafka-publish sequence with the transactional outbox pattern. The local sample keeps the sequence visible and compact, but a failure between the database commit and Kafka publication can otherwise leave an alert without an event.
Step 8: Implement the Response Service
Create response-service/pom.xml with Spring Boot web, JPA, PostgreSQL, Spring Kafka, actuator, validation, and shared-capabilities dependencies.
Create ResponseServiceApplication.java with the same filter and exception-handler imports used by the other services.
Create response-service/src/main/java/com/example/security/response/domain/SecurityResponse.java:
package com.example.security.response.domain;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.time.Instant;
@Entity
@Table(name = "security_responses")
public class SecurityResponse {
@Id
private String responseId;
private String tenantId;
private String alertId;
private String assetId;
private String action;
private String reason;
private String status;
private Instant createdAt;
protected SecurityResponse() {
}
public SecurityResponse(
String responseId,
String tenantId,
String alertId,
String assetId,
String action,
String reason,
String status,
Instant createdAt
) {
this.responseId = responseId;
this.tenantId = tenantId;
this.alertId = alertId;
this.assetId = assetId;
this.action = action;
this.reason = reason;
this.status = status;
this.createdAt = createdAt;
}
public String getResponseId() { return responseId; }
public String getTenantId() { return tenantId; }
public String getAlertId() { return alertId; }
public String getAssetId() { return assetId; }
public String getAction() { return action; }
public String getReason() { return reason; }
public String getStatus() { return status; }
public Instant getCreatedAt() { return createdAt; }
}
Create the repository:
package com.example.security.response.repository;
import com.example.security.response.domain.SecurityResponse;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SecurityResponseRepository extends JpaRepository<SecurityResponse, String> {
boolean existsByAlertId(String alertId);
}
Create an asset API client:
package com.example.security.response.service;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
@Component
public class AssetClient {
private final RestClient client = RestClient.builder()
.baseUrl("http://localhost:8082")
.build();
public AssetView get(String tenantId, String correlationId, String assetId) {
return client.get()
.uri("/api/v1/assets/{assetId}", assetId)
.header("X-Tenant-Id", tenantId)
.header("X-Correlation-Id", correlationId)
.header(HttpHeaders.ACCEPT, "application/json")
.retrieve()
.body(AssetView.class);
}
public record AssetView(
Long id,
String tenantId,
String assetId,
String hostname,
String criticality,
String ownerName
) {
}
}
Create the Kafka consumer:
package com.example.security.response.service;
import com.example.security.response.domain.SecurityResponse;
import com.example.security.response.repository.SecurityResponseRepository;
import com.example.security.shared.event.EventEnvelope;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.UUID;
@Service
public class AlertEventConsumer {
private final SecurityResponseRepository repository;
private final AssetClient assetClient;
public AlertEventConsumer(
SecurityResponseRepository repository,
AssetClient assetClient
) {
this.repository = repository;
this.assetClient = assetClient;
}
@KafkaListener(
topics = "security.alerts.v1",
groupId = "response-service-local"
)
public void consume(EventEnvelope<JsonNode> event) {
JsonNode payload = event.payload();
String alertId = payload.get("alertId").asText();
if (repository.existsByAlertId(alertId)) {
return;
}
String assetId = payload.get("assetId").asText();
String severity = payload.get("severity").asText();
AssetClient.AssetView asset = assetClient.get(
event.tenantId(),
event.correlationId(),
assetId
);
String action = decideAction(severity, asset.criticality());
String responseId = UUID.nameUUIDFromBytes(
(alertId + ":" + action).getBytes(StandardCharsets.UTF_8)
).toString();
SecurityResponse response = new SecurityResponse(
responseId,
event.tenantId(),
alertId,
assetId,
action,
"severity=" + severity + ", assetCriticality=" + asset.criticality(),
"DECIDED",
Instant.now()
);
repository.save(response);
}
private String decideAction(String severity, String criticality) {
if ("CRITICAL".equalsIgnoreCase(severity)
&& "CRITICAL".equalsIgnoreCase(criticality)) {
return "TEMPORARY_BLOCK_AND_ESCALATE";
}
if ("CRITICAL".equalsIgnoreCase(severity)
|| "HIGH".equalsIgnoreCase(severity)) {
return "ESCALATE_FOR_REVIEW";
}
return "MONITOR";
}
}
Create a read endpoint for local inspection:
package com.example.security.response.controller;
import com.example.security.response.domain.SecurityResponse;
import com.example.security.response.repository.SecurityResponseRepository;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/api/v1/responses")
public class ResponseController {
private final SecurityResponseRepository repository;
public ResponseController(SecurityResponseRepository repository) {
this.repository = repository;
}
@GetMapping
public List<SecurityResponse> list() {
return repository.findAll();
}
}
Create response-service/src/main/resources/application.yml:
server:
port: 8083
spring:
application:
name: response-service
datasource:
url: jdbc:postgresql://localhost:5435/response_db
username: response_user
password: response_password
jpa:
hibernate:
ddl-auto: update
open-in-view: false
kafka:
bootstrap-servers: localhost:9092
consumer:
auto-offset-reset: earliest
enable-auto-commit: false
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
value-deserializer: org.springframework.kafka.support.serializer.JsonDeserializer
properties:
spring.json.trusted.packages: com.example.security.shared.event,com.fasterxml.jackson.databind
listener:
ack-mode: record
management:
endpoints:
web:
exposure:
include: health,info,metrics
The response service owns the response policy. The shared library does not decide whether a critical asset should be blocked or escalated.
Step 9: Build All Modules
Build the Maven reactor from the project root:
mvn clean install
The build order should place shared-capabilities before the three services. Maven installs the shared JAR in the local repository and compiles each service against the same version.
If a service cannot find the shared library, verify that the service declares the dependency and that the build is running from the parent directory.
Step 10: Start the Three Services
Open three terminals in the project root.
Start the asset service:
mvn -pl asset-service spring-boot:run
Start the response service:
mvn -pl response-service spring-boot:run
Start the alert service:
mvn -pl alert-service spring-boot:run
Check health:
curl -s http://localhost:8081/actuator/health
curl -s http://localhost:8082/actuator/health
curl -s http://localhost:8083/actuator/health
The services run on ports 8081, 8082, and 8083. Their databases run on ports 5433, 5434, and 5435.
Step 11: Create an Asset and Publish an Alert
Create a critical asset:
curl -i -X POST http://localhost:8082/api/v1/assets \
-H 'Content-Type: application/json' \
-H 'X-Tenant-Id: tenant-a' \
-H 'X-Correlation-Id: local-flow-001' \
-d '{
"assetId": "server-001",
"hostname": "payments-api-01",
"criticality": "CRITICAL",
"ownerName": "Payment Platform Team"
}'
Retrieve the asset:
curl -s http://localhost:8082/api/v1/assets/server-001 \
-H 'X-Tenant-Id: tenant-a' \
-H 'X-Correlation-Id: local-flow-001'
Create a critical alert for the asset:
curl -i -X POST http://localhost:8081/api/v1/alerts \
-H 'Content-Type: application/json' \
-H 'X-Tenant-Id: tenant-a' \
-H 'X-Correlation-Id: local-flow-001' \
-d '{
"alertId": "alert-0001",
"assetId": "server-001",
"sourceIp": "203.0.113.40",
"severity": "CRITICAL",
"detectedAt": "2026-11-19T10:30:00Z"
}'
The alert service writes its own database record and publishes AlertCreated. The response service consumes the event, calls the asset service with the original tenant and correlation context, evaluates the policy, and stores a response decision.
Wait briefly and inspect the response:
curl -s http://localhost:8083/api/v1/responses \
-H 'X-Tenant-Id: tenant-a' \
-H 'X-Correlation-Id: local-flow-001'
The response action should be TEMPORARY_BLOCK_AND_ESCALATE because both the alert severity and asset criticality are critical.
Step 12: Verify Tenant Isolation and Correlation
Call the asset endpoint without X-Tenant-Id:
curl -i http://localhost:8082/api/v1/assets/server-001
The shared request-context filter should reject the request with HTTP 400.
Call the asset endpoint as another tenant:
curl -i http://localhost:8082/api/v1/assets/server-001 \
-H 'X-Tenant-Id: tenant-b' \
-H 'X-Correlation-Id: isolation-test-001'
The asset service should not return tenant-a data because its repository query includes tenant identity.
Inspect service logs for local-flow-001. The shared filter places the correlation and tenant identifiers in the logging MDC, allowing related HTTP work to be located consistently. Kafka also carries the correlation identifier inside the event envelope.
Step 13: Verify Independent Data Ownership
Inspect the alert database:
docker exec -it security-alert-db \
psql -U alert_user -d alert_db \
-c "SELECT alert_id, tenant_id, asset_id, severity, status FROM security_alerts;"
Inspect the asset database:
docker exec -it security-asset-db \
psql -U asset_user -d asset_db \
-c "SELECT asset_id, tenant_id, hostname, criticality FROM assets;"
Inspect the response database:
docker exec -it security-response-db \
psql -U response_user -d response_db \
-c "SELECT response_id, tenant_id, alert_id, asset_id, action, status FROM security_responses;"
Each database contains only the state owned by its service. The response service stores the asset identifier and the decision evidence it used but does not take ownership of the asset record.
Do not give one service the credentials of another service database. That operational rule is as important as the code boundary.
Step 14: Verify Idempotent Event Consumption
The response repository checks whether a response for the alert already exists. The response identifier is also deterministic for one alert and action.
Republish the same alert event through the alert API with the same alertId. PostgreSQL should reject the duplicate primary key in the alert service before another valid business record is created. If the same Kafka event is redelivered due to consumer restart or offset recovery, the response consumer detects the existing alert response and returns without inserting another record.
Inspect the response count:
docker exec -it security-response-db \
psql -U response_user -d response_db \
-c "SELECT alert_id, COUNT(*) FROM security_responses GROUP BY alert_id;"
The count for alert-0001 should remain one.
Step 15: Add Redis as a Shared Technical Capability Without Sharing Domain State
Redis is useful for technical acceleration, but services should not use one another's private cache keys. Assign a namespace to each service.
For asset lookup, use keys such as:
asset-service:v1:tenant:tenant-a:asset:server-001
For alert summaries, use keys such as:
alert-service:v1:tenant:tenant-a:summary:24h
For response suppression, use keys such as:
response-service:v1:tenant:tenant-a:alert:alert-0001:decision
A shared Redis helper can standardize serialization, key validation, timeouts, and metrics. It should not decide what an asset cache entry means or how long a response suppression decision remains valid. Those policies belong to the owning business service.
Add spring-boot-starter-data-redis only to services that need Redis. Configure the local connection:
spring:
data:
redis:
host: localhost
port: 6379
connect-timeout: 1s
timeout: 1s
Keep local cache timeouts short. A Redis failure should not make the service wait longer than the primary database or API operation it is intended to accelerate.
Step 16: Evolve the Shared Library Safely
Change the shared library version when its public contract changes. A backward-compatible addition can use a minor version. An incompatible change requires a major version and migration notes.
Do not add business entities such as SecurityAlert, Asset, or SecurityResponse to the shared library. This would force services to coordinate every domain-model change.
Prefer stable technical interfaces such as EventEnvelope, ApiError, RequestContext, correlation propagation, and common validation utilities.
After changing the shared library, rebuild it and the dependent modules:
mvn clean install
For a faster local build of only the library and services that depend on it:
mvn -pl shared-capabilities,alert-service,asset-service,response-service -am clean install
Before publishing a new library version in a real engineering environment, compile representative services against it and run their automated test suites. The local Maven reactor provides a basic version of this compatibility check.
Step 17: Prevent a Distributed Monolith
Do not make the alert-service request wait synchronously for the response service. Alert creation should succeed when Kafka accepts the event, even if the response service is temporarily stopped.
Do not import the asset service's JPA entity into the response service. Use the asset API contract or an asset event projection.
Do not require all services to deploy together. Each service should build a separate executable JAR and have independent configuration.
Do not create a shared database schema. Database joins across service boundaries create hidden release coupling.
Keep synchronous call chains short. The local response service makes one asset lookup because current criticality is required for the decision. If that lookup becomes a bottleneck, maintain a local asset-context projection in the response service by consuming asset events.
Do not place every dependency into one enterprise starter. Use focused shared modules so services import only the capabilities they need.
Step 18: Observe Service and Kafka Behavior
Inspect Kafka consumer groups:
docker exec -it security-module-kafka \
/opt/bitnami/kafka/bin/kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--list
Describe the response consumer group:
docker exec -it security-module-kafka \
/opt/bitnami/kafka/bin/kafka-consumer-groups.sh \
--bootstrap-server localhost:9092 \
--describe \
--group response-service-local
Inspect alert events:
docker exec -it security-module-kafka \
/opt/bitnami/kafka/bin/kafka-console-consumer.sh \
--bootstrap-server localhost:9092 \
--topic security.alerts.v1 \
--from-beginning \
--max-messages 1
Use each service's actuator metrics endpoint during local troubleshooting:
curl -s http://localhost:8081/actuator/metrics
curl -s http://localhost:8082/actuator/metrics
curl -s http://localhost:8083/actuator/metrics
A later shared observability starter can register Micrometer conventions and OpenTelemetry propagation. Keep business measurements in the owning service rather than inventing generic business metrics in the shared library.
Step 19: Test Service Independence Locally
Stop the response service while leaving alert and asset services running. Create another alert. The alert service should persist the alert and publish the event without waiting for response processing.
Restart the response service. Kafka should deliver the retained event, after which the response decision appears in the response database.
Stop the asset service and create another critical alert. The response consumer cannot obtain current asset context and should not guess. The Kafka listener should retry under a bounded error policy or leave the offset uncommitted until the dependency becomes available. Add a Spring Kafka DefaultErrorHandler with limited backoff before expanding the sample.
This behavior illustrates an important boundary. Independent deployment does not remove business dependencies. It makes those dependencies explicit and gives the system controlled ways to recover.
Step 20: Reset the Local Environment
Stop each Spring Boot process with Ctrl+C.
Stop infrastructure while preserving data:
docker compose stop
Restart it later:
docker compose start
Remove containers while retaining named volumes:
docker compose down
Remove containers and all local PostgreSQL, Redis, and Kafka data:
docker compose down -v
Delete local Maven build output if a completely clean rebuild is required:
find . -type d -name target -prune -exec rm -rf {} +
mvn clean install
The completed local environment demonstrates the intended architecture. The alert, asset, and response modules own different business decisions and different databases. Kafka carries an explicit business event between modules. HTTP is used only for a current asset lookup that requires an immediate answer. A shared library provides consistent tenant context, correlation, event envelopes, and error handling without absorbing domain policy. Each service can be changed, started, stopped, and scaled independently while retaining a common engineering foundation.
Top comments (0)