Practice workspace / Documentation
Try the app ↗ Source code ↗ Available offline
PROJECT GUIDE / LESSON 05

Understand the flow.
Build the next step.

Architecture, deployment and use of Messaging Lab.
From the first order to Kafka retries.

Prepare the environment
A COMPLETE WORKFLOW
01 Create an order HTTP or Kafka
02 Reserve inventory MySQL + idempotency
03 Observe the result Status, offset and DLT
05 application services 06 SVG diagrams 03 deployment modes Reviewed ·
01 · THE PROJECT

One application, two ways to communicate.

Messaging Lab is a learning environment for comparing synchronous HTTP and Kafka messaging through an orders and inventory scenario.

Operations

Orders and inventory

Create products, replenish inventory and confirm or reject orders according to available stock.

Lesson 04

Partitions and offsets

Publish batches with a shared key and observe their partition, offset and consumer.

Lesson 05

Retries and DLT

Simulate failures and observe consumption recovering or a record being forwarded to a Dead Letter Topic.

Reading path

  1. Prepare the environment. Choose Docker Desktop, local execution or Dokploy under Deployment.
  2. Complete a workflow. Create a product and compare HTTP and Kafka in the User guide.
  3. Understand what happens. Explore the architecture, classes, sequences and ER diagram; then review the API and limitations.
Technology Purpose and declared version
Java 21 · Maven Multi-module backend; Maven 3.9 in the build image.
Spring Boot 4.2.0 REST services, validation, JPA, Flyway and Spring Kafka.
Spring Cloud 2026.0.0 Reactive gateway with prefix-based routes.
React ^19.2.0 · Vite ^8.0.0 Client using Axios ^1.13.0. Node 24 and pnpm 12.21.0 in Docker.
MySQL · Kafka External infrastructure. The application's Compose files do not pin these versions.

Scope: repository version 1.0.0-SNAPSHOT, reviewed on 24 November 2026. This guide describes the code and configuration; it does not certify the availability of a remote environment.

02 · GETTING STARTED

Deployment step by step

Run commands from the repository root unless another directory is specified. The frontend is managed exclusively with pnpm.

Docker Desktop · practice environment

Install Docker Desktop. Keep MySQL on the Mac on port 3306 and connect the existing broker to mensajeria-local_mensajeria, with advertised listener kafka:29092. The MySQL user must be able to connect from the containers. If Kafka uses ACLs, enable the administrative and read operations required by kafka-retention, as well as producing and consuming.

1. Prepare the databases

On a new local installation, the script creates both databases, the lab user and permissions. Review it before applying it to an installation with existing users. Flyway creates the tables when the services start.

bash
mysql -u root -p < config/init-mysql.sql

2. Create or check the five topics

The following command uses the Kafka container named in the README. Adjust its name if your installation differs. It only creates missing topics; it does not change existing partitions.

bash
for topic in pedidos.creados.v1 inventario.resultados.v1 lab.particiones.v1 lab.errores.v1 lab.errores.v1.DLT; do
  docker exec mensajeria-local-kafka-1 /opt/kafka/bin/kafka-topics.sh \
    --bootstrap-server kafka:29092 --create --if-not-exists \
    --topic "$topic" --partitions 3 --replication-factor 1
  docker exec mensajeria-local-kafka-1 /opt/kafka/bin/kafka-topics.sh \
    --bootstrap-server kafka:29092 --describe --topic "$topic"
done

3. Configure and start

bash
cp .env.example .env
# Edita .env con las conexiones y credenciales de tu equipo.
docker compose config --quiet
docker compose up -d --build --wait --wait-timeout 240
docker compose ps -a

Open http://localhost:18080. The API is at http://localhost:10000. Published ports are bound to 127.0.0.1. Microservices communicate inside Docker.

The Java build runs Maven tests. The frontend is built with pnpm install --frozen-lockfile and Nginx serves the output. The first run requires access to dependency registries and repositories.

bash
docker compose logs -f
# Detener los cinco servicios de la aplicación.
docker compose down
# Reconstruir tras un cambio.
docker compose up -d --build --wait --wait-timeout 240

MySQL data and Kafka logs/offsets belong to the external infrastructure and remain when this application stops. The lab's in-memory history is lost on restart.

Local development · without application containers

Requirements: Java 21 or a later compatible version, Maven 3.9+, a Node version compatible with Vite 8 (Docker uses Node 24), pnpm, MySQL at localhost:3306, Kafka at localhost:9092 and the five topics listed above. Kafka credentials must also allow the active record cleanup described in the data model. Kafka scripts require their tools on PATH. Install the shared modules in the local Maven repository before starting each service.

bash
mysql -u root -p < config/init-mysql.sql
bash scripts/crear-topic-lab.sh
bash scripts/crear-topics-errores.sh
# Crea también pedidos.creados.v1 e inventario.resultados.v1 si no existen.
mvn clean test
mvn clean install -DskipTests

The two scripts only create the three lab topics. For the business topics, use kafka-topics.sh --bootstrap-server localhost:9092 --create --if-not-exists --topic NOMBRE --partitions 3 --replication-factor 1, replacing NOMBRE with each business topic.

In four separate terminals, from the repository root:

bash
mvn -pl ms-inventario spring-boot:run
# Otra terminal:
mvn -pl ms-pedidos spring-boot:run
# Otra terminal:
mvn -pl ms-kafka-lab spring-boot:run
# Otra terminal:
mvn -pl api-gateway spring-boot:run

In a fifth terminal:

bash
cd frontend
pnpm install --frozen-lockfile
pnpm dev

Open http://localhost:5173. Axios defaults to the Gateway at http://localhost:10000. VITE_API_URL can override this when starting Vite or at build time. The Gateway allows CORS from localhost and 127.0.0.1 on port 5173.

To practise only errors and partitions, you need only ms-kafka-lab, the Gateway and frontend. Business screens will not be available.

Dokploy · repository configuration

The file compose.production.yaml builds five services without publishing host ports. It reuses MySQL at mysql-mysqlcentral-azekcq:3306, network dokploy-network, and Kafka at kafka:9092, network kafka-net. These are settings for this installation, not services created by Compose.

  1. Prepare the infrastructure. Create the application databases with utf8mb4 and a dedicated user with migration permissions. Do not use root as the normal application user. Create or validate the five topics using the internal listener kafka:9092.
  2. Configure Git in Dokploy. Create a Docker Compose service, branch main, file compose.production.yaml and the repository URL given in the README. Images are built: do not use the Stack type.
  3. Fill in Environment. Copy the names from .env.production.example and set MYSQL_USER and MYSQL_PASSWORD. Preserve access to external networks.
  4. Prepare HTTPS. The DNS for msgkafkalab.acode.es must point to the server. Traefik requires web/websecure, the letsencrypt resolver and accessible ports 80/443. Compose already declares routes and HTTP → HTTPS redirection; avoid duplicating them in Domains.
  5. Deploy and verify. Click Deploy, check the five healthchecks and test inventory, an order and a lab event at https://msgkafkalab.acode.es.
bash
cp .env.production.example .env.production
# Completa las credenciales localmente; no las subas a Git.
docker compose --env-file .env.production -f compose.production.yaml config --quiet

Nginx forwards /api/ to the Gateway and preserves the original HTTPS protocol. To change the domain, review Compose labels as well as DNS and certificates.

Static documentation

Open docs/html/index.html directly in the browser. HTML, CSS, JavaScript and SVG diagrams are local; no installation or connection is required. To serve it over HTTP:

bash
python3 -m http.server 8088 --directory docs/html

Visit http://localhost:8088. To publish it, serve the contents of docs/html with any static server. This folder is not automatically copied into the frontend image.

03 · SYSTEM DESIGN

Architecture and responsibilities

Three business and learning microservices, an HTTP entry point and a React interface.

Component map
SVG ↓
Nginx → Gateway → microservices. Orders and Inventory have separate databases; Kafka connects producers and consumers.
Nginx → Gateway → microservices. Orders and Inventory have separate databases; Kafka connects producers and consumers.
Componente Responsibility Internal / local port
frontend Panels, forms, Axios requests and status polling. Nginx in Docker. 80 Docker / 5173 Vite
api-gateway Routes /api/pedidos/**, /api/inventario/** and /api/lab/kafka/**. Applies local CORS settings. 10000
ms-pedidos Persists orders and coordinates HTTP reservations or Kafka publication. Receives results. 10001
ms-inventario Manages the catalogue, replenishment and stock deductions; records Kafka reservations. 10002
ms-kafka-lab Generates batches, records received messages and simulates failures/retries/DLT. No MySQL. 10009

Code organisation

text
kafka-retention/   Biblioteca compartida de limpieza previa al envío
api-gateway/       Rutas y CORS
ms-pedidos/        Dominio Pedido, casos de uso y persistencia
ms-inventario/     Dominio Producto, catálogo y reservas
ms-kafka-lab/      Laboratorio independiente de mensajería
frontend/src/     React: App, api.js y components/
config/           Inicialización de bases MySQL
docker/           Dockerfile backend y configuración Nginx
scripts/          Herramientas de práctica Kafka
docs/html/        Esta documentación y sus diagramas

Within each microservice, domain defines models and exceptions; service coordinates use cases; repository adapts persistence; controller and dto expose HTTP; messaging translates events; config configures infrastructure where present. This is a simple DDD structure with concrete Spring dependencies in the application and adapter layers.

The library kafka-retention is shared by the three microservices and does not add a deployable service. It manages topic cleanup before each publication, including the DLT. See its rules under Data model and ER diagram.

In React, App.jsx composes the areas. PedidosPanel shares data through props; each panel manages its own state and requests. api.js centralises Axios. No global state store is used.

04 · CODE MODEL

Class diagram

A selection of existing classes for tracing the dependencies of the main use cases.

Classes and dependencies
SVG ↓
Arrows indicate usage. Records represent data, while repositories adapt persistent or in-memory access.
Arrows indicate usage. Records represent data, while repositories adapt persistent or in-memory access.

How to read the layers

PedidoController delegates to PedidoService. This uses InventarioClient for HTTP or PedidoKafkaProducer for Kafka, and persists through PedidoRepository → JpaPedidoRepository → PedidoEntity.

In Inventory, the HTTP flow goes through InventarioController → InventarioService → ProductoRepository → JpaProductoRepository. The Kafka flow goes through KafkaPedidoListener → ProcesarPedidoKafkaService → ReservaKafkaRepository, which coordinates the product and reservation JPA repositories within a transaction.

KafkaResultadoListener delegates to ResultadoInventarioService, which only accepts CONFIRMADO/RECHAZADO and updates orders that are still PENDIENTE.

In the lab, KafkaErroresController publishes through KafkaErrorProducer. KafkaErrorListener calls ProcesadorFallosService; KafkaErroresConfig installs the error handler. KafkaDltListener observes the DLT and updates ErroresRegistroRepository in memory. The partitions lab uses LaboratorioService, KafkaLabProducer, KafkaLabListener and RecepcionRepository.

05 · BEHAVIOUR

From click to result

The diagrams show the main flow. Errors and transaction boundaries explain why an order may remain pending.

01 / HTTP reservation
SVG ↓
Orders waits for the reservation, saves the confirmed order and returns 201. If the reservation returns a conflict, it does not create the order.
Orders waits for the reservation, saves the confirmed order and returns 201. If the reservation returns a conflict, it does not create the order.
02 / Kafka order
SVG ↓
PENDIENTE is persisted, the request is published and 202 is returned. Inventory saves the reservation result and publishes the response. Consumption may occur before the 202 reaches the browser.
PENDIENTE is persisted, the request is published and 202 is returned. Inventory saves the reservation result and publishes the response. Consumption may occur before the 202 reaches the browser.

The reservation is deduplicated by pedido_id. If the same order reappears with the same SKU and quantity, the previous result is returned. If they differ, the duplicate is rejected with an exception. A race when inserting the same identifier also rolls back the stock deduction of the failing transaction.

The result is published after persisting the reservation. If publication fails, redelivery allows the result to be recovered without deducting stock again. In Orders, an update conditional on PENDIENTE prevents modifying a final state again.

03 / Retries and recovery
SVG ↓
PERMANENTE exhausts three deliveries and is copied to the DLT. INVALIDO is forwarded after the first delivery; TRANSITORIO recovers on the third.
PERMANENTE exhausts three deliveries and is copied to the DLT. INVALIDO is forwarded after the first delivery; TRANSITORIO recovers on the third.

The lab retries are blocking: DefaultErrorHandler uses FixedBackOff(1000, 2). There are no intermediate retry topics or @RetryableTopic. Partition progress may stop during these retries.

06 · PERSISTENCE

Data model and ER diagram

Flyway migrations are the schema source. Three business tables are split across two MySQL databases.

Entities, keys and associations
SVG ↓
Dashed lines: logical relationships. There are no declared foreign keys between these tables or databases.
Dashed lines: logical relationships. There are no declared foreign keys between these tables or databases.
Table Key and fields Relevant rules
orders id BIGINT auto-increment PK; cliente VARCHAR(120); importe DECIMAL(12,2); estado VARCHAR(20); creado_en DATETIME(6); sku VARCHAR(40); cantidad INTEGER. sku and cantidad allow NULL under migration V2 for compatibility with older records. New orders require them.
productos sku VARCHAR(40) PK; nombre VARCHAR(150); disponible INTEGER. All NOT NULL. Unique SKU. The service prevents negative initial stock and non-positive replenishment.
reservas_kafka pedido_id BIGINT PK; sku VARCHAR(120); cantidad INT; estado VARCHAR(30); motivo VARCHAR(120). All NOT NULL. One persisted result per Kafka order. It can record rejection for an unknown SKU; it has no foreign key to productos.

Migrations and initial data

Orders: V1__crear_pedidos.sql creates the table and V2__pedido_producto.sql adds SKU/quantity. Inventory: V1__productos.sql creates the catalogue with TECLADO-01 (10), RATON-01 (5) and MONITOR-01 (2); V2__reservas_kafka.sql adds the idempotency table. These data are inserted when V1 is applied, not reset at each startup.

Flyway applies changes and maintains its technical history table for each database; Hibernate is set to ddl-auto: validate. Do not edit migrations that have already been applied: add another version and test the upgrade on a copy of the data.

Application-driven retention

The shared module kafka-retention, imported by all three microservices, replaces KafkaTemplate with RetentionKafkaTemplate. Before sending (including to the DLT), TopicRetention adds up the differences between end and beginning offsets across partitions. At 5,000, it deletes batches of up to 1,000 old records and measures again. This is active cleanup using Admin.deleteRecords, in addition to broker retention.

It selects old records by comparing timestamps at the head of each partition, without bypassing internal ordering. Sending is locked per topic within each JVM; this is not a strict global limit against producers in other instances. The offset difference approximates the number of retained records.

Kafka must allow topic description, offset queries, record reading and deletion, in addition to normal producing and consuming. If querying or cleanup fails, sending fails before publication. The DLT configures setFailIfSendResultIsError(true) to propagate a recoverer send failure.

What persists and what is lost

Almacenamiento Information After restarting the application
External MySQL Products, stock, orders and Kafka reservation results. Retained on the existing MySQL server.
External Kafka Records, partitions and group offsets. Subject to broker retention and active kafka-retention cleanup. Deleted records are no longer available for replay.
ms-kafka-lab memory Received messages, counters, states and observed DLT messages. Lost; not automatically rebuilt as a complete history.
07 · OPERATING GUIDE

User guide

A practical walkthrough of the screens and actions available in the current interface.

1. Create the catalogue and replenish stock

  1. Go to Orders and inventory → Inventory and click New product.
  2. Enter a unique SKU, for example AURICULARES-01, a name and a non-negative integer initial stock.
  3. Save. The product appears in inventory and in the order form selector.
  4. Click Replenish in its row, enter a positive integer quantity and confirm. The quantity is added to current stock.

A SKU supports up to 40 characters: letters, numbers, dots, hyphens and underscores; it must start with a letter or number. Names support up to 150 characters. Maximum availability is 2,147,483,647. A duplicate SKU returns 409 without changing units.

2. Create an order and compare modes

  1. Open the orders area and the form New order.
  2. Choose Asynchronous Kafka (default) or Synchronous HTTP (lesson 2).
  3. Enter the customer, product, positive integer quantity and an amount of at least €0.01. The amount is the entered total; it is not calculated from a catalogue price.
  4. Click Create order and inspect the orders table and stock.
Modo Initial response Visible result
HTTP 201: order confirmed after reservation. CONFIRMADO; 409 conflict if it cannot reserve. It may return 503 if Inventory is unavailable.
Kafka 202: order accepted for processing. PENDIENTE → CONFIRMADO or RECHAZADO when the result is consumed. The response does not guarantee stock.

To check both paths, use a product with stock 3, create an order for 1 unit and observe stock falling to 2. Then request more units than are available: HTTP returns a conflict; Kafka ends as RECHAZADO and preserves stock. Query again if the asynchronous result takes time to appear.

3. Observe partitions and offsets

  1. Open Kafka lab → Partitions and offsets.
  2. Enter a key, for example cliente-42, and a batch of 1 to 100 messages.
  3. Click Publish batch. Compare partition and offset in confirmed publications and received messages.
  4. Repeat with the same key, then another. The same key is assigned consistently while partitioning conditions remain unchanged; two different keys may share a partition.

The panel polls every 3 seconds while active and shows at most 30 received messages. An offset identifies a position within a partition; it does not order the whole topic. History belongs to this instance, not all group members.

4. Test errors and DLT

Open Kafka lab → Retries and Dead Letter Topic, choose the behaviour and click Publish test event. The panel polls states and DLT every 2 seconds while active. Identify each test by its eventoId.

Modo Expected deliveries Observed final state DLT
EXITOSO 1 PROCESADO No
TRANSITORIO 3; the first two fail PROCESADO No
PERMANENTE 3; all fail DLT when observed by the monitor Yes
INVALIDO 1; non-retryable IllegalArgumentException DLT when observed by the monitor Yes

A published message may still be processing. Publication confirmation does not imply consumer success. Restarting or clearing memory changes simulator counters and may affect the TRANSITORIO demonstration.

5. Clear practice data

The API can only clear the error lab's counters, states and observed DLT entries. It does not delete Kafka messages, change offsets or clear partition history. This version's frontend does not offer a form for deleting products or orders.

bash
curl -i -X DELETE http://localhost:10000/api/lab/kafka/errores/memoria
08 · INTEGRATIONS

API reference

Local base: http://localhost:10000. In Docker and Dokploy, the browser can use /api/ on the frontend's own origin. Request bodies are JSON.

Method Route JSON body / fields Success response
GET /api/pedidos — 200 · list of orders
POST /api/pedidos cliente, importe, sku, cantidad 201 · order CONFIRMADO
POST /api/pedidos/async cliente, importe, sku, cantidad 202 · order initially PENDIENTE
GET /api/inventario/productos — 200 · list of products
POST /api/inventario/productos sku, nombre, disponible 201 · product created
POST /api/inventario/productos/{sku}/reposiciones cantidad 200 · product updated
POST /api/inventario/reservas sku, cantidad 201 · no body
GET /api/lab/kafka/estado — 200 · instance, group, partitions
GET /api/lab/kafka/recepciones — 200 · local history
POST /api/lab/kafka/publicaciones clave, cantidad (1–100) 201 · list of publications
POST /api/lab/kafka/errores/publicar clave, modo, optional descripcion 202 · eventoId, topic, particion, offset, modo
GET /api/lab/kafka/errores/estados — 200 · local states
GET /api/lab/kafka/errores/dlt — 200 · observed DLT messages
GET /api/lab/kafka/errores/configuracion — 200 · configuration information
DELETE /api/lab/kafka/errores/memoria — 204 · no body

Reproducible examples

The following examples modify practice data. Use a new SKU if the example SKU already exists.

bash
# Crear catálogo.
curl -i -X POST http://localhost:10000/api/inventario/productos \
  -H 'Content-Type: application/json' \
  -d '{"sku":"DOC-DEMO-01","nombre":"Producto de prueba","disponible":10}'

# Crear un pedido Kafka.
curl -i -X POST http://localhost:10000/api/pedidos/async \
  -H 'Content-Type: application/json' \
  -d '{"cliente":"Ana","importe":29.90,"sku":"DOC-DEMO-01","cantidad":2}'

# Consultar el resultado después del consumo.
curl -sS http://localhost:10000/api/pedidos
curl -sS http://localhost:10000/api/inventario/productos

# Reponer 5 unidades.
curl -i -X POST http://localhost:10000/api/inventario/productos/DOC-DEMO-01/reposiciones \
  -H 'Content-Type: application/json' -d '{"cantidad":5}'

# Simular fallo permanente y consultar la DLT.
curl -i -X POST http://localhost:10000/api/lab/kafka/errores/publicar \
  -H 'Content-Type: application/json' \
  -d '{"clave":"ensayo-docs","modo":"PERMANENTE","descripcion":"Demostración DLT"}'
curl -sS http://localhost:10000/api/lab/kafka/errores/estados
curl -sS http://localhost:10000/api/lab/kafka/errores/dlt

Interpreting errors

Code Situation
400 Body validation or input rules: invalid quantity, SKU, amount or mode; also replenishment exceeding the maximum.
404 Product not found during replenishment.
409 Duplicate SKU or insufficient stock, depending on the endpoint.
502 / 503 In Orders: unexpected Inventory response / Inventory connection failure or timeout.
5xx Technical failure not mapped by a specific handler, such as a failed Kafka publication. An HTTP error does not prove that the order was not saved.

Custom handlers usually return {"error":"…"}. Not all errors share a single schema. The frontend also checks detail or the Axios message. The API does not declare pagination or general update/deletion endpoints for orders/products.

09 · EVENT CONTRACTS

Topics, groups and guarantees

Business events are serialised as version 1 JSON and use pedidoId as the Kafka key.

Topic Producer → consumer Consumer group
orders.creados.v1 PedidoKafkaProducer → KafkaPedidoListener ms-inventario-reservas-v1
inventario.resultados.v1 ResultadoKafkaProducer → KafkaResultadoListener ms-orders-resultados-v1
lab.particiones.v1 KafkaLabProducer → KafkaLabListener LAB_GROUP; defaults to lab-grupo-a
lab.errores.v1 KafkaErrorProducer → KafkaErrorListener lab-errores-grupo-v1
lab.errores.v1.DLT DeadLetterPublishingRecoverer → KafkaDltListener lab-errores-dlt-monitor-v1
Illustrative JSON (explanatory comments)
// pedidos.creados.v1 · clave "42"
{"version":1,"pedidoId":42,"sku":"TECLADO-01","cantidad":2}

// inventario.resultados.v1 · clave "42"
{"version":1,"pedidoId":42,"estado":"CONFIRMADO","motivo":"OK"}

// Alternativa: reserva rechazada
{"version":1,"pedidoId":42,"estado":"RECHAZADO","motivo":"STOCK_INSUFICIENTE_O_SKU_INVALIDO"}

// lab.errores.v1 · clave del ensayo
{"version":1,"eventoId":"uuid","clave":"ensayo-docs","modo":"PERMANENTE","descripcion":"Prueba"}

Shared publication and retention

Producers use RetentionKafkaTemplate → TopicRetention before sending. Every publication arrow in the diagrams includes this preliminary check. The library does not directly change group offsets, but deleting records can leave consumer offsets behind the start of the log.

What this implementation guarantees

Producers declare acks: all and Kafka idempotence, while listeners acknowledge each record (ack-mode: record). Producer idempotence prevents some duplicate sends but does not provide a single transaction spanning Kafka and MySQL.

Business protection resides in reservas_kafka.pedido_id and in order state changes conditional on PENDIENTE. auto-offset-reset: earliest applies when no valid offset exists; restarting a consumer does not automatically replay every message.

Limitations to understand

  • No Outbox: saving the order and publishing are not atomic. A send failure may leave an order persisted as PENDIENTE without a confirmed event.
  • No distributed transaction: the HTTP flow also has no compensation if saving after the reservation fails.
  • The DLT belongs to the lab: this same custom policy is not declared for Orders/Inventory consumers.
  • No automatic DLT reprocessing: the monitor only observes. Deleting local history does not resend records.
  • No global exactly-once guarantee: redeliveries are allowed, with part of their domain effect controlled.
10 · SETTINGS

Environment configuration

Specific values depend on whether the process runs on the host, in Docker Desktop or in Dokploy.

Variable Usage Value / note
MYSQL_USER · MYSQL_PASSWORD Orders and Inventory connections. Configure a dedicated user; do not publish secrets.
MYSQL_URL Full JDBC URL for Orders when running Java. Defaults to localhost:3306/messaging_lab_pedidos.
INVENTARIO_MYSQL_URL Full JDBC URL for Inventory when running Java. Defaults to localhost:3306/messaging_lab_inventario.
MYSQL_HOST · MYSQL_PORT Compose files construct the JDBC URLs. Docker: host.docker.internal:3306. Dokploy: the installation's MySQL host.
MYSQL_PEDIDOS_DATABASE · MYSQL_INVENTARIO_DATABASE Database names in production Compose. messaging_lab_pedidos / messaging_lab_inventario.
MYSQL_NETWORK External MySQL network in production. dokploy-network.
KAFKA_BOOTSTRAP_SERVERS Listener accessible from the services. Local: localhost:9092; Docker: kafka:29092; Dokploy: kafka:9092.
KAFKA_NETWORK External Compose Kafka network. mensajeria-local_mensajeria in Docker; kafka-net in production.
FRONTEND_PORT · GATEWAY_PORT Ports published by local Compose. 18080 / 10000. Not published in production Compose.
PEDIDOS_URL · INVENTARIO_URL · KAFKA_LAB_URL Gateway destinations; INVENTARIO_URL also configures the Orders client. Compose resolves them through service names.
VITE_API_URL Frontend Axios base, at development/build time. Defaults to http://localhost:10000; Docker image: /. Changing it requires rebuilding.
LAB_INSTANCE · LAB_GROUP Partition lab instance and group identity. Local: lab-A / lab-grupo-a. Compose sets the instance to lab-docker or lab-produccion.
LAB_CONSUMER_ENABLED · LAB_DELAY_MS Partition listener activation and delay. true / 0. These do not affect the error listener; export locally or add to Compose environment.
11 · MAINTENANCE

Operations and troubleshooting

Start with availability, continue with connectivity and finish with business state.

Quick check

bash
docker compose ps -a
docker compose logs --tail=100 api-gateway ms-pedidos ms-inventario ms-kafka-lab
curl -fsS http://localhost:10000/actuator/health
curl -fsS http://localhost:10000/api/inventario/productos
curl -fsS http://localhost:18080/healthz

# Salud de cada Java desde su propio contenedor.
docker compose exec ms-pedidos curl -fsS http://localhost:10001/actuator/health
docker compose exec ms-inventario curl -fsS http://localhost:10002/actuator/health
docker compose exec ms-kafka-lab curl -fsS http://localhost:10009/actuator/health

The Gateway and microservices expose Actuator health/info. Gateway health describes the Gateway itself: also verify business routes and consumers. /healthz checks Nginx. In production, health details are hidden and container logs rotate (10 MB, 3 files).

Symptom What to check
Compose cannot find the network The Kafka network is external: verify that it exists and matches KAFKA_NETWORK. In production, also validate MySQL and Traefik networks.
Unhealthy container / JDBC error MySQL availability, existing databases, user access from Docker and Flyway permissions. Check migration errors and credentials.
Kafka does not connect from Docker Advertised listener and network DNS. localhost inside a container refers to that container, not the Mac.
Order remains PENDIENTE for a long time Broker, topic existence, kafka-retention read/delete permissions, and logs of both consumers and groups. A failure between persistence and publication is also possible; there is no automatic reconciler.
An event does not reach the DLT Check partition count, failure mode and ms-kafka-lab logs. EXITOSO and TRANSITORIO should not end up in the DLT.
Empty history after restart History is local memory. A group with committed offsets continues from its position without rebuilding the complete history.
Frontend cannot access the API In Vite, check Gateway :10000 and CORS origin :5173. In Docker, verify Nginx and the / base built into the image.
Port already in use Adjust FRONTEND_PORT or GATEWAY_PORT in .env and recreate the services. Keep the same values in operational commands.

Inspect consumption and DLT

The following scripts require Kafka tools on the host's PATH and use localhost:9092 unless you export another bootstrap:

bash
bash scripts/ver-grupos.sh
bash scripts/ver-grupo-errores.sh
bash scripts/leer-dlt.sh
# El consumidor DLT permanece escuchando; usa Ctrl+C para salir.

For Docker, you can run the tool directly in the existing container:

bash
docker exec mensajeria-local-kafka-1 /opt/kafka/bin/kafka-consumer-groups.sh \
  --bootstrap-server kafka:29092 --describe --group lab-errores-grupo-v1

docker exec mensajeria-local-kafka-1 /opt/kafka/bin/kafka-console-consumer.sh \
  --bootstrap-server kafka:29092 --topic lab.errores.v1.DLT --from-beginning \
  --property print.key=true --property print.partition=true --property print.offset=true

Backup and evolution

Back up both MySQL databases and retain Kafka infrastructure according to its retention policies. Backups are managed outside this application's Compose files. Active kafka-retention cleanup can delete business and DLT records even when consumers are lagging. Assess its impact before relying on Kafka as a historical archive. Test restores and new migrations in a separate environment. Do not delete topics or reset offsets to solve an interface problem.

12 · QUALITY AND REFERENCES

Verification and evolution

Project validation commands and a map of the sources used to maintain this documentation.

Validate application changes

bash
# Desde la raíz: tests Java del proyecto multimódulo.
mvn clean test

# Desde frontend: instalación reproducible y empaquetado.
cd frontend
pnpm install --frozen-lockfile
pnpm build

There are tests in Orders (PedidoServiceTest, FlujoKafkaTest), Inventory (InventarioServiceTest, ProcesarPedidoKafkaServiceTest) and Lab (LaboratorioServiceTest, ProcesadorFallosServiceTest). A build or unit test does not replace end-to-end verification against real MySQL and Kafka instances.

Acceptance walkthrough

  1. Confirm the health of all five services and that the catalogue can be read.
  2. Create a SKU, replenish stock and verify that it persists after restarting the application.
  3. Create one HTTP and one Kafka order; verify states and stock deductions.
  4. Request more units than are available: verify an HTTP conflict and a Kafka rejection.
  5. Publish a batch and verify partition/offset.
  6. Run all four error modes and compare attempts and DLT with the guide.

Repository sources

Fuente What it documents
README.md Purpose, exercises, infrastructure and operational steps.
compose.yaml · compose.production.yaml Services, networks, ports, healthchecks and deployment.
.env.example · .env.production.example Variables supported by Compose files.
TopicRetention.java Active topic cleanup before sending.
pom.xml · frontend/package.json Modules and technology versions.
SQL Pedidos V1 · V2 Physical orders schema.
SQL Inventory V1 · V2 Catalogue, seed data and reservations.
PedidoService.java · ReservaKafkaRepository.java Flows, transactions and idempotency.
KafkaErroresConfig.java Actual retry and DLT policy.

Source links work when this folder is viewed inside the repository. If you publish only docs/html, pages and diagrams still work, but those source references require a repository copy or replacement with links to its Git hosting.

Documentation design

Inspired by the supplied Modella CRM colour guide: warm background #FAF9F7, cream navigation #F4F0EC, white cards, sage accent #7EA199 and accessible primary #466D65. Inter is declared with a system fallback and no font downloads. Includes visible focus, keyboard navigation, responsive layout and print styles.

Glossary

Term Meaning
Topic A logical Kafka log divided into partitions.
Partition / offset An ordering unit and the position of a record within it.
Consumer group Members that divide a topic's partitions among themselves for consumption.
DLT A topic receiving records that could not be processed under the lab's policy.
Idempotency Processing a repeat without repeating the intended business effect.
DER A diagram of data entities, attributes and relationships.
Outbox A pattern for coordinating persistence and publication through a transactional record. It is not implemented here.

Project licence: MIT. For further technical evolution, consider Outbox, pending-order reconciliation, observability, access control and a validated DLT reprocessing process.

Diagram

Use +/− to adjust the scale and scroll to explore. Press Escape to close.

CV & portfolio · ES / EN
EspañolEnglish