Skip to content

Enterprise-grade, event-sourced Order Book implementation using CQRS (Command Query Responsibility Segregation) and Event Sourcing patterns with Axon Framework.

License

Notifications You must be signed in to change notification settings

prasadus92/order-book

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Order Book

Java Version Spring Boot Axon Framework License

Enterprise-grade, event-sourced Order Book implementation using CQRS (Command Query Responsibility Segregation) and Event Sourcing patterns with Axon Framework.

Architecture Overview

┌─────────────────────────────────────────────────────────────────────────────┐
│                              API Gateway / Load Balancer                     │
└─────────────────────────────────┬───────────────────────────────────────────┘
                                  │
                    ┌─────────────┴─────────────┐
                    │                           │
                    ▼                           ▼
        ┌───────────────────┐       ┌───────────────────┐
        │  Command Service  │       │  Query Service    │
        │     (Port 8081)   │       │    (Port 8082)    │
        │                   │       │                   │
        │  • Place Orders   │       │  • Get Orders     │
        │  • Update Status  │       │  • List Orders    │
        │  • Cancel Orders  │       │  • Statistics     │
        └─────────┬─────────┘       └─────────┬─────────┘
                  │                           │
                  │    ┌─────────────────┐    │
                  │    │    RabbitMQ     │    │
                  ├───►│  Event Broker   │────┤
                  │    │                 │    │
                  │    └─────────────────┘    │
                  │                           │
                  ▼                           ▼
        ┌───────────────────┐       ┌───────────────────┐
        │     MongoDB       │       │     MongoDB       │
        │   Event Store     │       │   Read Model      │
        │                   │       │                   │
        │  • Domain Events  │       │  • Order Views    │
        │  • Snapshots      │       │  • Indexes        │
        └───────────────────┘       └───────────────────┘

Key Features

  • Event Sourcing: Complete audit trail of all order state changes
  • CQRS Pattern: Optimized read and write paths for scalability
  • Axon Framework: Production-ready event sourcing and DDD support
  • MongoDB: Flexible document store for events and read models
  • RabbitMQ: Reliable async event distribution
  • OpenAPI 3.0: Interactive API documentation with Swagger UI
  • Observability: Prometheus metrics, health checks, structured logging
  • Docker Ready: Full containerization with docker-compose

Project Structure

order-book/
├── common/                    # Shared module
│   └── src/main/java/
│       └── rise/trader/orderbook/common/
│           ├── command/       # Command definitions
│           ├── event/         # Event definitions
│           ├── domain/        # Domain value objects
│           ├── query/         # Query definitions
│           ├── exception/     # Shared exceptions
│           └── validation/    # Business rule validators
│
├── command-service/           # Write side (CQRS Command)
│   └── src/main/java/
│       └── rise/trader/orderbook/command/
│           ├── aggregate/     # Axon aggregates
│           ├── api/           # REST controllers & DTOs
│           ├── config/        # Configuration classes
│           └── exception/     # Exception handlers
│
├── query-service/             # Read side (CQRS Query)
│   └── src/main/java/
│       └── rise/trader/orderbook/query/
│           ├── api/           # REST controllers & DTOs
│           ├── config/        # Configuration classes
│           ├── domain/        # Read model entities
│           ├── projection/    # Event projections
│           └── repository/    # MongoDB repositories
│
├── docker/                    # Docker configurations
├── docs/                      # Documentation
└── pom.xml                    # Parent POM

Technology Stack

Component Technology Version
Language Java 17
Framework Spring Boot 3.2.2
Event Sourcing Axon Framework 4.9.3
Database MongoDB 7.0
Message Broker RabbitMQ 3.12
Build Tool Maven 3.9+
API Docs SpringDoc OpenAPI 2.3.0
Containerization Docker 24+

Getting Started

Prerequisites

  • Java 17 or later
  • Maven 3.9 or later
  • Docker and Docker Compose (for local development)

Quick Start with Docker

# Clone the repository
git clone https://github.com/prasadus92/order-book.git
cd order-book

# Start infrastructure (MongoDB, RabbitMQ)
docker-compose up -d mongodb rabbitmq

# Build and run services
./mvnw clean package -DskipTests
docker-compose up -d

Local Development

# Start infrastructure
docker-compose up -d mongodb rabbitmq

# Build the project
./mvnw clean install

# Run Command Service
./mvnw spring-boot:run -pl command-service

# Run Query Service (in another terminal)
./mvnw spring-boot:run -pl query-service

API Documentation

Once the services are running, access the Swagger UI:

Command Service Endpoints

Method Endpoint Description
POST /api/v1/orders Place a new order
PUT /api/v1/orders/{id}/status Update order status
DELETE /api/v1/orders/{id} Cancel an order
GET /api/v1/orders/{id}/events Get order event history

Query Service Endpoints

Method Endpoint Description
GET /api/v1/orders List all orders (paginated)
GET /api/v1/orders/{id} Get order by ID
GET /api/v1/orders/pending Get pending orders
GET /api/v1/orders/user/{userId} Get orders by user
GET /api/v1/orders/statistics Get order statistics

Order Lifecycle

┌──────────┐    ┌───────────┐    ┌──────────────────┐    ┌────────┐
│  PLACED  │───►│ SUBMITTED │───►│ PARTIALLY_FILLED │───►│ FILLED │
└──────────┘    └───────────┘    └──────────────────┘    └────────┘
     │               │                    │
     │               │                    │
     ▼               ▼                    ▼
┌─────────────────────────────────────────────────────────────────┐
│                      CANCEL_SUBMITTED                            │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
                        ┌───────────┐
                        │ CANCELLED │
                        └───────────┘

Example Usage

Place a New Order

curl -X POST http://localhost:8081/api/v1/orders \
  -H "Content-Type: application/json" \
  -d '{
    "account": {
      "userId": "user-123",
      "exchangeAccountId": "binance-456"
    },
    "symbol": {
      "exchange": "BINANCE",
      "baseAsset": "BTC",
      "quoteAsset": "USD"
    },
    "quantity": 1.5,
    "side": "BUY",
    "limitPrice": 50000.00
  }'

Get Order Details

curl http://localhost:8082/api/v1/orders/{orderId}

Update Order Status

curl -X PUT http://localhost:8081/api/v1/orders/{orderId}/status \
  -H "Content-Type: application/json" \
  -d '{
    "status": "SUBMITTED"
  }'

Cancel an Order

curl -X DELETE http://localhost:8081/api/v1/orders/{orderId}?reason=User%20requested

Configuration

Environment Variables

Variable Description Default
MONGODB_URI MongoDB connection URI mongodb://localhost:27017/orderbook
RABBITMQ_HOST RabbitMQ host localhost
RABBITMQ_PORT RabbitMQ port 5672
RABBITMQ_USERNAME RabbitMQ username guest
RABBITMQ_PASSWORD RabbitMQ password guest

Observability

Health Checks

Metrics (Prometheus)

Testing

# Run all tests
./mvnw test

# Run tests with coverage report
./mvnw verify

# Coverage reports will be in target/site/jacoco/

Building for Production

# Build optimized JARs
./mvnw clean package -Pprod

# Build Docker images
docker build -t order-book-command:latest -f docker/Dockerfile.command .
docker build -t order-book-query:latest -f docker/Dockerfile.query .

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

About

Enterprise-grade, event-sourced Order Book implementation using CQRS (Command Query Responsibility Segregation) and Event Sourcing patterns with Axon Framework.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •