> ## Documentation Index
> Fetch the complete documentation index at: https://docs.0xmonaco.com/llms.txt
> Use this file to discover all available pages before exploring further.

# V0.5.1

# Monaco Protocol v0.5.1

> **Note:** These are historical release notes for v0.5.1 and describe the architecture as it shipped at that time. Redis (and its ElastiCache deployment) has since been removed. The current architecture is PostgreSQL (durable source of truth) + NATS JetStream (durable log and pub/sub fan-out) + an in-memory matching engine (DashMap). References to Redis below reflect the v0.5.1 design only.

## Architecture Evolution

This release marks a significant evolution in Monaco's infrastructure, transitioning from a monolithic API to a **distributed microservices architecture** designed for high-frequency trading workloads.

### High-Level Architecture

```
                                    +------------------+
                                    |   Application    |
                                    |   Load Balancer  |
                                    +--------+---------+
                                             |
                    +------------------------+------------------------+
                    |                        |                        |
                    v                        v                        v
           +---------------+        +---------------+        +---------------+
           |   HTTP API    |        |  WebSocket    |        |   gRPC API    |
           |   (REST)      |        |     API       |        | (Proto/HTTP2) |
           |  Port 8080    |        |  Port 8080    |        |  Port 50051   |
           +-------+-------+        +-------+-------+        +-------+-------+
                   |                        |                        |
                   +------------------------+------------------------+
                                            |
                                            v
                               +------------------------+
                               |    Matching Engine     |
                               |   (Order Processing)   |
                               +------------------------+
                                            |
                    +------------------------+------------------------+
                    |                                                 |
                    v                                                 v
           +---------------+                                 +---------------+
           |    Redis      |                                 |  PostgreSQL   |
           | (Hot Path)    |                                 | (Persistence) |
           +---------------+                                 +---------------+
```

### Microservices Breakdown

| Service | Purpose | Protocol | Port |
| - | - | - | - |
| **api-gateway-rust** | REST API for trading, accounts, market data | HTTP/1.1, HTTPS | 8080 |
| **ws-api** | Real-time orderbook & trade streaming | WebSocket | 8080 |
| **grpc-api** | High-performance trading API | gRPC/HTTP2 | 50051 |
| **matching-engine** | Order matching & trade execution | Internal | - |

### Path-Based Routing

All services are accessible through a single domain with intelligent path-based routing:

```
https://{host}/                        → REST API (api-gateway)
wss://{host}/ws                        → WebSocket API (ws-api)
https://{host}                         → gRPC API over HTTP/2 method paths (grpc-api)
```

***

## Performance Architecture

### The Monaco Speed Layer

Monaco achieves sub-millisecond order processing through a carefully designed **dual-storage architecture**:

```
                          Order Flow
                              |
                              v
                    +-------------------+
                    |  Balance Check &  |
                    |   Lock (Atomic)   |  <-- Redis (< 1ms)
                    +-------------------+
                              |
                              v
                    +-------------------+
                    |  Order Matching   |
                    |   (In-Memory)     |  <-- Matching Engine
                    +-------------------+
                              |
                              v
                    +-------------------+
                    |  Trade Settlement |
                    |    (Atomic)       |  <-- Redis (< 1ms)
                    +-------------------+
                              |
                              v
                    +-------------------+
                    |   Persistence     |
                    |  (Fire & Forget)  |  <-- PostgreSQL (async)
                    +-------------------+
```

**Key Innovation**: Our proprietary Redis layer handles all balance operations with **custom atomic scripts** that ensure consistency while maintaining sub-millisecond latency. This allows us to process the entire order lifecycle—from balance validation to trade settlement—without waiting for database round-trips.

### Latency Targets

| Operation | Target | Description |
| - | - | - |
| Balance Lock | \< 1ms | Atomic check-and-lock |
| Order Matching | \< 1ms | In-memory orderbook |
| Trade Settlement | \< 2ms | Multi-party atomic update |
| Total E2E | \< 5ms | Full order lifecycle |

***

## Real-Time Data Streaming

### WebSocket Architecture

The dedicated WebSocket service provides real-time market data with minimal latency:

```
+-------------+     +----------+     +---------------+     +--------+
|   Client    | <-> |    ALB   | <-> |    ws-api     | <-> |  Redis |
| (Browser/   |     | (Sticky  |     | (Pub/Sub      |     | Pub/Sub|
|  Bot)       |     |  Session)|     |  Consumer)    |     |        |
+-------------+     +----------+     +---------------+     +--------+
                                            ^
                                            |
                                     +---------------+
                                     |   Matching    |
                                     |   Engine      |
                                     | (Publisher)   |
                                     +---------------+
```

**Available Channels:**

* `orderbook:{trading_pair_id}` - Real-time orderbook updates
* `trades:{trading_pair_id}` - Trade executions
* `user:{user_id}` - Private order updates

***

## gRPC API (New)

### Why gRPC?

| Feature | REST | gRPC |
| - | - | - |
| Serialization | JSON (text) | Protobuf (binary) |
| Connection | HTTP/1.1 (new per request) | HTTP/2 (multiplexed) |
| Typing | Runtime validation | Compile-time types |
| Streaming | Polling/WebSocket | Native bidirectional |

### Quick Start

```typescript theme={null}
import * as grpc from '@grpc/grpc-js';

const client = new proto.public_api.v1.OrdersService(
  'staging.apimonaco.xyz:443',
  grpc.credentials.createSsl()
);

// Create order with sub-5ms latency
const order = await client.CreateOrder({
  trading_pair_id: 'uuid',
  order_type: 'LIMIT',
  side: 'BUY',
  price: '50000.00',
  quantity: '0.1',
  time_in_force: 'GTC'
}, metadata);
```

### Service Reference

| Service | Methods | Auth |
| - | - | - |
| `AuthService` | Challenge, Verify, Refresh, Revoke | No |
| `OrdersService` | Create, Cancel, Replace, List | JWT |
| `AccountsService` | Profile, Balances, Movements | JWT |
| `MarketDataService` | Pairs, Orderbook, Trades, Candles | No |
| `TransfersService` | Deposit/Withdraw signatures | JWT |

***

## Deployment Architecture

### Container Orchestration

Each microservice runs as an independent ECS service with auto-scaling:

```
+------------------------------------------+
|              AWS ECS Cluster             |
|                                          |
|  +-------------+  +-------------+        |
|  | api-gateway |  | api-gateway |  x N   |
|  |   Task 1    |  |   Task 2    |        |
|  +-------------+  +-------------+        |
|                                          |
|  +-------------+  +-------------+        |
|  |   ws-api    |  |   ws-api    |  x N   |
|  |   Task 1    |  |   Task 2    |        |
|  +-------------+  +-------------+        |
|                                          |
|  +-------------+  +-------------+        |
|  |  grpc-api   |  |  grpc-api   |  x N   |
|  |   Task 1    |  |   Task 2    |        |
|  +-------------+  +-------------+        |
|                                          |
|  +-------------+                         |
|  |  matching   |  (Single instance       |
|  |   engine    |   per trading pair)     |
|  +-------------+                         |
+------------------------------------------+
```

### Horizontal Scaling

* **Stateless APIs**: HTTP, WebSocket, and gRPC services scale horizontally
* **Matching Engine**: Partitioned by quote token for parallel processing
* **Redis**: ElastiCache cluster with read replicas
* **PostgreSQL**: RDS with read replicas for query scaling

***

## Migration Guide

### From v0.5.0

No breaking changes. The REST API remains fully compatible. New services are additive:

1. **WebSocket**: Now on dedicated service (improved reliability)
2. **gRPC**: New option for latency-sensitive applications

### Choosing Your API

| Use Case | Recommended API |
| - | - |
| Web applications | REST + WebSocket |
| Mobile apps | REST + WebSocket |
| Trading bots | gRPC |
| Market makers | gRPC + WebSocket |
| Backend services | gRPC |

***

## What's Next

* **Streaming gRPC**: Server-side streaming for real-time data
* **FIX Protocol**: Industry-standard trading protocol support
* **Colocation**: Reduced latency for institutional traders

***

*For detailed API documentation, see the [REST API](/api-reference) or [WebSocket API](/websocket) sections.*


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.