Skip to content

About

Event-driven microservices system for asynchronous order processing. Built with NestJS, RabbitMQ, PostgreSQL, Docker and Prisma ORM. Features separated API and Worker services with message-based communication for scalable architecture.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

🧩 Payment Microservices System

A backend project that demonstrates a microservices architecture using NestJS, RabbitMQ, Docker, PostgreSQL, and Prisma ORM. This project was built to showcase real-world backend architecture concepts such as event-driven systems, Saga pattern (Choreography), asynchronous processing, and distributed transaction management.

NestJS RabbitMQ PostgreSQL Prisma Docker TypeScript Prometheus Grafana CI

Grafana dashboard: Microservices Overview The provisioned Grafana dashboard after 3 minutes of npm run traffic (~4 orders/s): 650 orders, 82% payment approval, zero 5xx, zero dead-lettered messages. See Observability.


📐 Architecture

This project implements a microservices architecture with an API Gateway that routes communication between services using both synchronous HTTP (for queries) and asynchronous events (for commands).

graph LR
    Client[Client] -->|HTTP| GW[API Gateway]

    GW -->|Events| RMQ[RabbitMQ]
    GW -.->|HTTP| Order[Order Service]
    GW -.->|HTTP| Payment[Payment Service]

    RMQ <-->|Events| Order
    RMQ <-->|Events| Payment

    Order --> OrderDB[(PostgreSQL<br/>Order DB)]
    Payment --> PaymentDB[(PostgreSQL<br/>Payment DB)]

    style GW fill:#4A90E2,color:#fff
    style RMQ fill:#FF6B35,color:#fff
    style Order fill:#50C878,color:#fff
    style Payment fill:#50C878,color:#fff
    style OrderDB fill:#9B59B6,color:#fff
    style PaymentDB fill:#9B59B6,color:#fff
Loading

Architecture Highlights

  • API Gateway: Single entry point for all client requests (port 3000)
  • Event-Driven Commands: POST/PATCH operations emit events via RabbitMQ
  • Synchronous Queries: GET operations make direct HTTP calls to microservices
  • Saga Pattern (Choreography): Distributed transactions coordinated through events, with compensating actions for cancellations
  • Light hexagonal design in the order and payment services: domain entities and ports only where there is an external dependency (database, payment provider); reads stay plain Prisma queries
  • Service Autonomy: Each microservice has its own database and business logic
  • Decoupled Communication: Services communicate through events, not direct calls

🏗️ Project Structure

payment-microservice/
├── apps/
│   ├── api-gateway/                 # API Gateway (Port 3000)
│   │   └── src/
│   │       ├── common/
│   │       │   ├── http/            # Downstream HTTP client + error mapping
│   │       │   └── middleware/      # Correlation ID
│   │       ├── config/              # Environment schema (validated at boot)
│   │       ├── modules/
│   │       │   ├── health/
│   │       │   ├── metrics/
│   │       │   ├── orders/
│   │       │   │   └── dto/
│   │       │   └── payments/
│   │       ├── app.module.ts
│   │       └── main.ts
│   │
│   ├── order-service/               # Order Microservice (Port 3001)
│   │   ├── prisma/                  # Schema, migrations, generated client
│   │   └── src/
│   │       ├── config/
│   │       ├── modules/
│   │       │   ├── health/
│   │       │   ├── metrics/
│   │       │   └── order/
│   │       │       ├── domain/      # Order entity, state machine, repository port
│   │       │       ├── application/ # Use cases, queries, reconciliation job
│   │       │       ├── infra/       # Prisma repositories, outbox event mapping
│   │       │       ├── consumers/   # Main + DLQ consumers
│   │       │       ├── controllers/
│   │       │       └── dto/
│   │       ├── app.module.ts
│   │       ├── main.ts
│   │       └── replay-dlq.ts        # DLQ replay CLI
│   │
│   └── payment-service/             # Payment Microservice (Port 3002)
│       ├── prisma/
│       └── src/
│           ├── config/
│           ├── modules/
│           │   ├── health/
│           │   ├── metrics/
│           │   └── payment/
│           │       ├── domain/      # Payment entity, state machine, repository + gateway ports
│           │       ├── application/ # Use cases, queries, reconciliation job
│           │       ├── infra/       # Prisma repositories, simulated gateway, outbox mapping
│           │       ├── consumers/
│           │       ├── controllers/
│           │       └── dto/
│           ├── app.module.ts
│           ├── main.ts
│           └── replay-dlq.ts        # DLQ replay CLI
│
├── libs/
│   ├── contracts/                   # Shared contracts, split by domain
│   │   ├── order-events/            # Order domain events, types, and cancel reasons
│   │   └── payment-events/          # Payment domain events and types
│   │
│   ├── messaging/                   # Shared messaging building blocks
│   │   ├── rabbitmq/
│   │   │   ├── config/              # Connection, exchanges, full queue topology
│   │   │   ├── constants/           # Exchanges, queues, routing keys, DLQs
│   │   │   ├── error-handling/      # Bounded retries + dead-lettering (publisher confirms)
│   │   │   └── publishing/          # publishEvent: persistent + correlationId
│   │   ├── outbox/                  # Transactional outbox records + relay
│   │   ├── dlq/                     # Dead letter replay
│   │   └── database/                # Raw SQL client interface shared by the jobs
│   │
│   └── common/                      # Shared utilities
│       ├── config/                  # Env validation helpers
│       ├── context/                 # Correlation ID (AsyncLocalStorage)
│       ├── events/                  # Generic BaseEvent
│       ├── health/                  # Database / RabbitMQ health checks
│       ├── logger/                  # Correlation-aware logger
│       ├── messaging/
│       └── metrics/                 # MetricNames (event_type label values)
│
├── monitoring/                      # Prometheus config + provisioned Grafana
│   ├── grafana/
│   │   └── provisioning/            # Datasource + Microservices Overview dashboard
│   └── prometheus.yml
│
├── scripts/
│   └── generate-traffic.mjs         # Load generator for the dashboard
│
├── .github/workflows/ci.yml         # Lint, type-check, tests, build
├── docker-compose.yml
└── README.md

🚀 Features

✅ API Gateway

  • Single entry point for all client requests
  • Routes queries (GET) directly to microservices via HTTP
  • Emits commands as events via RabbitMQ exchanges without knowledge of downstream queues
  • Generates the orderId and returns it immediately (202 Accepted), so clients can track the order
  • Validates input: request bodies via DTOs and every :id / :orderId as a UUID (400 otherwise)
  • Maps downstream failures to gateway status codes (see Error Responses)
  • Propagates a correlation ID (x-correlation-id) through HTTP calls and events

✅ Order Service

  • Manages the order lifecycle with an explicit state machine:
    PENDING_PAYMENT ──► PAID ──► CANCELLED   (user cancel, payment refunded)
           │
           ├──► CANCELLED                    (user cancel)
           └──► FAILED                       (payment declined or failed)
    
    CANCELLED and FAILED are terminal. A declined payment makes the order FAILED, not CANCELLED: CANCELLED only ever means the user cancelled it
  • Consumes order.create.requested and order.cancel.requested to create and cancel orders
  • A cancel that arrives before the order exists creates it directly as CANCELLED (a tombstone, with no userId/total), so the create request that arrives later does nothing
  • Consumes payment.approved, payment.declined, payment.failed to update the order status, and payment.refunded only to record it (log + metric)
  • Emits order.created and order.cancelled (user cancellations only) through the outbox
  • RESTful API for order queries (GET endpoints)
  • Isolated PostgreSQL database

✅ Payment Service

  • Manages the payment lifecycle with an explicit state machine:
    PROCESSING ──► APPROVED ──► REFUNDED   (order cancelled after payment)
        │
        ├──► DECLINED                      (gateway declined; the reason is stored in failureReason)
        ├──► FAILED                        (unexpected gateway error; failureReason too)
        └──► CANCELLED                     (order cancelled while processing)
    
    DECLINED, FAILED, REFUNDED and CANCELLED are terminal
  • Consumes order.created to charge the payment and order.cancelled to cancel or refund it
  • A cancel that arrives before order.created writes a CANCELLED tombstone payment (no amount), so the order.created that arrives later never charges
  • Charges in two steps, like real card processors: authorize reserves the amount and capture takes it only after the approval is recorded. If the cancel wins the race while an authorization is in flight, the authorization is voided, so the customer is never charged
  • Emits payment.approved, payment.declined, payment.failed and payment.refunded through the outbox
  • The provider sits behind a PaymentGateway port (authorize(paymentId, amountCents), capture(paymentId), release(paymentId) to void or refund, with paymentId as the idempotency key). The bundled SimulatedPaymentGateway has ~1.5s latency and declines ~20% for insufficient funds
  • Amounts are integers in cents (amountCents)
  • Provides payment statistics and queries
  • Isolated PostgreSQL database

✅ Event-Driven Architecture

  • RabbitMQ topic exchanges (orders.exchange, payments.exchange) for asynchronous pub/sub
  • Each service owns its queues and binds them to the routing keys it consumes
  • No shared queues between services
  • The whole topology (queues, bindings, DLQs) is declared by every service at boot
  • Durable queues and persistent messages

✅ Reliability Patterns

  • Idempotency by business key: orders are keyed by the orderId the gateway generates and payments are unique per orderId, so a redelivered message finds the existing record instead of creating a duplicate, and does nothing if it was already processed
  • State machine with conditional updates: every status change goes through the state machine and is saved only if the record still has the status it was read with, so concurrent events (e.g. a cancel racing a payment approval) cannot both win
  • Tombstones: a cancel handled before the record it cancels exists (separate queues, no ordering) writes a CANCELLED record with the same key; the create that arrives later finds it and neither creates the order nor charges the customer
  • Transactional outbox: an event is written to outbox_messages in the same transaction as the state change it announces; a relay publishes pending rows (polling with FOR UPDATE SKIP LOCKED, safe with several instances) and marks them published after the broker confirms. Delivery is at-least-once, so consumers stay idempotent
  • Retry with delay + DLQ + replay: a failing message is retried 3 times, 5 seconds apart (through a <queue>.retry TTL queue), then sent to the service's DLQ and persisted in failed_messages with the real error (requeued if the database is down). Once the cause is fixed, the replay CLI republishes them to their original queue
  • Reconciliation: a scheduled job resumes payments stuck in PROCESSING and reports orders stuck in PENDING_PAYMENT (orders_stuck_pending_payment gauge) after RECONCILIATION_STUCK_AFTER_MINUTES
  • Persistent messages: every publish goes through publishEvent, which always sets persistent: true (durable queues alone do not survive a broker restart) and the correlation ID
  • Publisher confirms: the outbox relay, the retry handler and the replay only consider a message sent once the broker confirms it; the retry handler acks the original message only after its republish is confirmed
  • Health checks (database + RabbitMQ) used by Docker Compose, graceful shutdown on SIGTERM, and environment validation at boot

✅ Saga Pattern (Choreography)

  • Happy path: order.create.requested → order.created → payment.approved → order PAID
  • Failure path: payment.declined or payment.failed → order FAILED. Nothing is published back: the payment is already final, so there is nothing to compensate
  • Compensating transaction: order.cancel.requested → order CANCELLED → order.cancelled → payment CANCELLED (if still processing) or refunded → REFUNDED + payment.refunded (if already approved)
  • Out-of-order cancel: if the cancel is handled first, a CANCELLED tombstone takes the key in the order service and/or the payment service, and the late create is a no-op
  • No central coordinator: each service reacts to domain events via its own queues and emits new events

Messaging Design

Exchange Routing key Published by Consumed by (queue)
orders.exchange order.create.requested API Gateway Order Service (order.create.queue)
orders.exchange order.cancel.requested API Gateway Order Service (order.cancel-requested.queue)
orders.exchange order.created Order Service Payment Service (payment.order-created.queue)
orders.exchange order.cancelled Order Service Payment Service (payment.order-cancelled.queue)
payments.exchange payment.approved / payment.declined / payment.failed / payment.refunded Payment Service Order Service (order.payment-result.queue)

Each queue has a <queue>.retry companion and a dead-letter queue bound on dlx.exchange (e.g. order.create.dlq).


🛠️ Technologies

Technology Purpose
NestJS Backend framework for building scalable Node.js applications
TypeScript Type-safe language for robust code
RabbitMQ Message broker for event-driven architecture
PostgreSQL Relational database for order and payment data
Prisma ORM Type-safe database access and migrations
Prometheus Metrics collection (services + RabbitMQ)
Grafana Provisioned dashboard
Jest Unit tests
GitHub Actions CI: lint, type-check, tests, build
Docker Containerization for consistent environments
Docker Compose Multi-container orchestration

📦 Installation

Prerequisites

  • Docker and Docker Compose
  • Node.js 20+ and npm (only for local development, tests, and the traffic generator)

Steps

  1. Clone the repository
   git clone https://github.com/luchersou/payment-microservice.git
   cd payment-microservice
  1. Start everything with Docker Compose (services, databases, RabbitMQ, Prometheus, Grafana)
   docker compose up --build

Migrations run automatically on startup. If port 3000 is already in use, pick another host port for the gateway:

   API_GATEWAY_PORT=3010 docker compose up --build
  1. Install dependencies locally (optional: for tests, lint, and npm run traffic)
   npm install

Ports

Service URL
API Gateway http://localhost:3000/api
Order Service http://localhost:3001
Payment Service http://localhost:3002
Grafana http://localhost:3003
Prometheus http://localhost:9090
RabbitMQ Management http://localhost:15672
Order DB / Payment DB localhost:5433 / localhost:5434

Environment Variables

Validated at boot: a service with an invalid or missing variable fails to start and lists every problem. Docker Compose sets them for you.

Variable Used by Default
PORT all 3000 / 3001 / 3002
RABBITMQ_URL all amqp://localhost:5672
DATABASE_URL order, payment required (postgresql://...)
ORDER_SERVICE_URL gateway http://localhost:3001
PAYMENT_SERVICE_URL gateway http://localhost:3002
REQUEST_TIMEOUT gateway 5000 (ms)
OUTBOX_POLL_INTERVAL_MS order, payment 1000
OUTBOX_BATCH_SIZE order, payment 100
OUTBOX_PUBLISH_TIMEOUT_MS order, payment 5000
RECONCILIATION_INTERVAL_MS order, payment 60000
RECONCILIATION_STUCK_AFTER_MINUTES order, payment 5

📊 Observability

The stack ships with Prometheus and a provisioned Grafana dashboard. Nothing to import.

Tool URL Credentials
Grafana (dashboard Microservices → Microservices Overview) http://localhost:3003 admin / admin123
Prometheus (Status → Targets) http://localhost:9090 —
RabbitMQ Management http://localhost:15672 admin / admin123

Generate traffic so the panels have data (needs the stack running and npm install):

npm run traffic                          # ~2 orders/s for 2 minutes
npm run traffic -- --duration 60 --rate 5
GATEWAY_URL=http://localhost:3010/api npm run traffic   # custom gateway port

The dashboard has five sections:

  • Overview: services up, orders created, payment approval rate, gateway 5xx rate, retries and dead-lettered messages
  • Business: orders and payments per second by outcome
  • API Gateway (HTTP): requests by route, responses by status code, p95 latency
  • Messaging (RabbitMQ): p95 processing time per event, queue depth (including *.retry and *.dlq), failed messages by outcome
  • Runtime (Node.js): CPU, memory and event loop lag per service
Full dashboard screenshot

Grafana dashboard: all sections

Scraped endpoints: api-gateway:3000/api/metrics, order-service:3001/metrics, payment-service:3002/metrics, and RabbitMQ's built-in exporter (rabbitmq:15692/metrics/detailed).


🔌 API Endpoints

All requests go through the API Gateway on http://localhost:3000/api

📋 Orders

Method Endpoint Description
POST /orders Create an order (emits event, returns orderId)
GET /orders Get all orders (paginated, page / limit ≤ 100)
GET /orders/:id Get order by ID
PATCH /orders/:id/cancel Cancel an order (emits event)

💳 Payments

Method Endpoint Description
GET /payments Get all payments (paginated)
GET /payments/:id Get payment by ID
GET /payments/order/:orderId Get payment by order ID
GET /payments/stats Get payment statistics by status

⚙️ Operations

Method Endpoint Description
GET /health Gateway health (RabbitMQ). Services expose GET /health with database + RabbitMQ
GET /metrics Prometheus metrics

❗ Error Responses

Status When
400 Bad Request Invalid body or an :id that is not a UUID
404 Not Found Order or payment does not exist
502 Bad Gateway A downstream service returned 5xx
503 Service Unavailable A downstream service is unreachable
504 Gateway Timeout A downstream service did not answer within REQUEST_TIMEOUT

📡 Event Flow

Create Order Flow

1. Client → POST /api/orders
2. API Gateway → Generate orderId
               → Emit order.create.requested → RabbitMQ
               → Respond 202 with orderId

3. Order Service → Consume order.create.requested
   - Persist order (status: PENDING_PAYMENT) + order.created in the outbox (one transaction)
   - Outbox relay → Emit order.created → RabbitMQ
   - If a tombstone already holds the orderId (cancelled first) → nothing

4. Payment Service → Consume order.created
   - Create payment (status: PROCESSING)
   - If a tombstone already holds the orderId (cancelled first) → never charge
   - Authorize through the PaymentGateway (paymentId as idempotency key)

5. Payment Service → Save the result + its event in the outbox, then emit:
   - payment.approved (and only then capture the authorized amount)
   - OR payment.declined (reason kept in failureReason)
   - OR payment.failed

6. Order Service → Consume payment event
   - Update order status:
     - payment.approved → PAID
     - payment.declined → FAILED
     - payment.failed   → FAILED

Cancel Order Flow

1. Client → PATCH /api/orders/:id/cancel
2. API Gateway → Emit order.cancel.requested → RabbitMQ

3. Order Service → Consume order.cancel.requested
   - If PENDING_PAYMENT or PAID → Update order status → CANCELLED
                                → Emit order.cancelled (outbox) → RabbitMQ
   - If it does not exist yet   → Create it as CANCELLED (tombstone)
                                → Emit order.cancelled
   - If FAILED → Ignore (terminal)

4. Payment Service → Consume order.cancelled
   - If PROCESSING   → Mark as CANCELLED
                       (an authorization still in flight is voided when it
                        returns: the customer is never charged)
   - If APPROVED     → Release through the gateway (refund) → Mark as REFUNDED
                     → Emit payment.refunded
   - If it does not exist yet → Create it as CANCELLED (tombstone, no amount)
   - Otherwise       → Ignore

5. Order Service → Consume payment.refunded → log + metric only

🧪 Example Requests

📋 Orders

Create Order

POST http://localhost:3000/api/orders
Content-Type: application/json

{
  "userId": "d55fa6d6-63c2-4633-aeaf-ecf0c80fb48f",
  "totalCents": 1999
}

cURL:

curl -X POST http://localhost:3000/api/orders \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "d55fa6d6-63c2-4633-aeaf-ecf0c80fb48f",
    "totalCents": 1999
  }'

totalCents is an integer amount in cents (1999 = 19.99); a decimal value is rejected with 400.

Response: 202 Accepted. The order is created asynchronously; use the orderId to follow it:

{
    "orderId": "476f5730-aa83-4ff0-ab9f-d6e19836e195",
    "message": "Order creation request accepted",
    "status": "PENDING_PAYMENT"
}

Get All Orders (Paginated)

GET http://localhost:3000/api/orders?page=1&limit=10

cURL:

curl "http://localhost:3000/api/orders?page=1&limit=10"

Response:

{
  "data": [
    {
      "id": "476f5730-aa83-4ff0-ab9f-d6e19836e195",
      "userId": "d55fa6d6-63c2-4633-aeaf-ecf0c80fb48f",
      "totalCents": 1999,
      "status": "PAID",
      "createdAt": "2026-02-15T01:42:19.000Z",
      "updatedAt": "2026-02-15T01:42:21.000Z"
    },
    {
      "id": "b7740f92-e574-4936-aa23-56f98ba61418",
      "userId": "d55fa6d6-63c2-4633-aeaf-ecf0c80fb48f",
      "totalCents": 1999,
      "status": "CANCELLED",
      "createdAt": "2026-02-15T01:42:39.000Z",
      "updatedAt": "2026-02-15T01:42:40.000Z"
    }
  ],
  "meta": {
    "page": 1,
    "limit": 10,
    "total": 2,
    "totalPages": 1
  }
}

Get Order by ID

GET http://localhost:3000/api/orders/476f5730-aa83-4ff0-ab9f-d6e19836e195

cURL:

curl http://localhost:3000/api/orders/476f5730-aa83-4ff0-ab9f-d6e19836e195

Response:

{
  "id": "476f5730-aa83-4ff0-ab9f-d6e19836e195",
  "userId": "d55fa6d6-63c2-4633-aeaf-ecf0c80fb48f",
  "totalCents": 1999,
  "status": "PAID",
  "createdAt": "2026-02-15T01:42:19.000Z",
  "updatedAt": "2026-02-15T01:42:21.000Z"
}

Cancel Order

PATCH http://localhost:3000/api/orders/476f5730-aa83-4ff0-ab9f-d6e19836e195/cancel

cURL: (no body)

curl -X PATCH http://localhost:3000/api/orders/476f5730-aa83-4ff0-ab9f-d6e19836e195/cancel

Response: 202 Accepted

{
    "orderId": "476f5730-aa83-4ff0-ab9f-d6e19836e195",
    "message": "Order cancellation request accepted"
}

💳 Payments

Get All Payments (Paginated)

GET http://localhost:3000/api/payments?page=1&limit=10

cURL:

curl "http://localhost:3000/api/payments?page=1&limit=10"

Response:

{
  "data": [
    {
      "id": "8a5da4d7-3512-4c74-bd62-64b6c0e93e7a",
      "orderId": "476f5730-aa83-4ff0-ab9f-d6e19836e195",
      "amountCents": 1999,
      "status": "APPROVED",
      "failureReason": null,
      "createdAt": "2026-02-15T01:42:19.500Z",
      "updatedAt": "2026-02-15T01:42:20.500Z"
    },
    {
      "id": "1220b65f-df5f-456d-8238-e03520bff097",
      "orderId": "b7740f92-e574-4936-aa23-56f98ba61418",
      "amountCents": 1999,
      "status": "DECLINED",
      "failureReason": "Insufficient funds",
      "createdAt": "2026-02-15T01:42:39.200Z",
      "updatedAt": "2026-02-15T01:42:40.200Z"
    }
  ],
  "meta": {
    "page": 1,
    "limit": 10,
    "total": 2,
    "totalPages": 1
  }
}

Get Payment by ID

GET http://localhost:3000/api/payments/8a5da4d7-3512-4c74-bd62-64b6c0e93e7a

cURL:

curl http://localhost:3000/api/payments/8a5da4d7-3512-4c74-bd62-64b6c0e93e7a

Response:

{
  "id": "8a5da4d7-3512-4c74-bd62-64b6c0e93e7a",
  "orderId": "476f5730-aa83-4ff0-ab9f-d6e19836e195",
  "amountCents": 1999,
  "status": "APPROVED",
  "failureReason": null,
  "createdAt": "2026-02-15T01:42:19.500Z",
  "updatedAt": "2026-02-15T01:42:20.500Z"
}

Get Payment by Order ID

GET http://localhost:3000/api/payments/order/476f5730-aa83-4ff0-ab9f-d6e19836e195

cURL:

curl http://localhost:3000/api/payments/order/476f5730-aa83-4ff0-ab9f-d6e19836e195

Response:

{
  "id": "8a5da4d7-3512-4c74-bd62-64b6c0e93e7a",
  "orderId": "476f5730-aa83-4ff0-ab9f-d6e19836e195",
  "amountCents": 1999,
  "status": "APPROVED",
  "failureReason": null,
  "createdAt": "2026-02-15T01:42:19.500Z",
  "updatedAt": "2026-02-15T01:42:20.500Z"
}

Get Payment Statistics

GET http://localhost:3000/api/payments/stats

cURL:

curl http://localhost:3000/api/payments/stats

Response:

{
  "byStatus": [
    {
      "status": "APPROVED",
      "count": 2,
      "totalAmountCents": 3998
    },
    {
      "status": "DECLINED",
      "count": 1,
      "totalAmountCents": 1999
    }
  ]
}

🧑‍💻 Development

npm test               # unit tests (Jest)
npm run lint:check     # lint without fixing (npm run lint fixes)
npm run typecheck      # type-check, including specs
npm run build          # build libs and the three apps

CI runs the same four steps on every pull request and push to main.

To run a service outside Docker, start the infrastructure with docker compose up -d order-db payment-db rabbitmq and set the environment variables for that service, e.g. for the order service:

DATABASE_URL=postgresql://admin:admin123@localhost:5433/order_db \
RABBITMQ_URL=amqp://admin:admin123@localhost:5672 \
npm run start:order:dev

DLQ replay

Dead letters stay in each service's failed_messages table. After fixing what made them fail, republish them to the queue whose consumer gave up on them (rows are marked replayedAt; a message that fails again comes back as a new row):

# inside the running container
docker exec payment-service node /app/dist/apps/payment-service/src/replay-dlq.js
docker exec order-service node /app/dist/apps/order-service/src/replay-dlq.js --queue order.payment-result.dlq --limit 50

# or locally, after npm run build, with DATABASE_URL and RABBITMQ_URL set
npm run dlq:replay:payment -- --limit 100

🏛️ Design Patterns Used

  • Microservices Architecture: Independent services with isolated databases
  • API Gateway Pattern: Single entry point for client requests
  • Event-Driven Architecture: Asynchronous communication via RabbitMQ
  • Saga Pattern (Choreography): Distributed transactions with compensating actions across services
  • State Machine: Explicit, atomically enforced status transitions for orders and payments
  • Idempotent Consumer: Safe handling of redelivered messages, by business key
  • Tombstone: Out-of-order cancels recorded before the entity exists
  • Transactional Outbox: State change and event committed together
  • Retry + Dead Letter Queue + Replay: Bounded, delayed retries before isolating poison messages, and a way to reprocess them
  • Ports and Adapters (light): Repository and payment gateway ports, Prisma and simulated adapters

📄 License

This project is licensed under the MIT License.


👤 Author

Lucas Herzinger Souza

About

Event-driven microservices system for asynchronous order processing. Built with NestJS, RabbitMQ, PostgreSQL, Docker and Prisma ORM. Features separated API and Worker services with message-based communication for scalable architecture.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages