Compare commits

...

12 Commits

10 changed files with 405 additions and 36 deletions

103
README.md
View File

@ -1,26 +1,97 @@
# Rinha Backend 2025
## 📖 Sobre o Projeto
A scalable backend application built with [NestJS](https://nestjs.com/), using TypeScript, Redis for fast in-memory
operations, and SQL for persistent storage.
Este é um projeto desenvolvido para a [Rinha de Backend - 2025](https://github.com/zanfranceschi/rinha-de-backend-2025/), focado em alta performance e escalabilidade para processamento de pagamentos em massa. O sistema foi projetado para lidar com picos de até **500 requisições por segundo** mantendo consistência e confiabilidade.
## Features
### 🎯 Objetivo
- 🚀 Fast, modular API with NestJS
- 💾 Payments queueing and processing with Redis
- 🗄️ Persistent data with SQL database
- 🐳 Dockerized for easy deployment
Criar uma API robusta capaz de processar pagamentos de forma assíncrona, garantindo:
## Getting Started
- **Idempotência**: Evita pagamentos duplicados
- **Resiliência**: Fallback automático entre processadores
- **Escalabilidade**: Múltiplas instâncias com load balancing
- **Performance**: Processamento em fila com alta concorrência
### Prerequisites
## 🛠️ Tecnologias Utilizadas
- [Node.js](https://nodejs.org/) (v22+)
- [Yarn](https://yarnpkg.com/) or [npm](https://www.npmjs.com/)
- [Docker](https://www.docker.com/) & [Docker Compose](https://docs.docker.com/compose/)
### **Backend Framework**
- **[NestJS](https://nestjs.com/)** - Framework Node.js robusto e escalável
- **[TypeScript](https://www.typescriptlang.org/)** - Tipagem estática para maior confiabilidade
### **Banco de Dados**
- **[PostgreSQL 17](https://www.postgresql.org/)** - Banco relacional otimizado para alta performance
- **[TypeORM](https://typeorm.io/)** - ORM para TypeScript/JavaScript
### **Queue e Cache**
- **[Redis 7.2](https://redis.io/)** - Armazenamento em memória para cache e filas
- **[BullMQ](https://docs.bullmq.io/)** - Sistema de filas robusto para processamento assíncrono
### **Load Balancing**
- **[Nginx](https://nginx.org/)** - Reverse proxy e load balancer
- **Algoritmo least_conn** - Distribuição inteligente de requisições
### **Infraestrutura**
- **[Docker](https://www.docker.com/)** - Containerização da aplicação
- **[Docker Compose](https://docs.docker.com/compose/)** - Orquestração de múltiplos serviços
### **Otimizações Aplicadas**
- ⚡ **UNLOGGED Tables** - Performance máxima em inserts
- 🔄 **Connection Pooling** - Reutilização eficiente de conexões
- 📊 **Query Optimization** - Índices únicos e queries SQL diretas
- 🛡️ **Rate Limiting** - Proteção contra sobrecarga
- 🔁 **Circuit Breaker** - Tolerância a falhas
- 📝 **Retry com Backoff** - Reprocessamento inteligente
### 🔄 Fluxo de Processamento
1. **Recepção**: Nginx distribui requisições entre as 3 instâncias da API
2. **Enfileiramento**: Pagamentos são adicionados na fila Redis (BullMQ)
3. **Processamento**: Workers consomem a fila e tentam processar via:
- Processador principal (default)
- Processador de fallback (se o principal falhar)
4. **Persistência**: Pagamentos bem-sucedidos são salvos no PostgreSQL
5. **Idempotência**: Sistema evita duplicação via `correlation_id` único
## 📋 Arquitetura e Recursos dos Serviços
| Serviço | Imagem | CPU | Memória | Porta | Descrição |
| ------------ | ------------------------------------ | ---------- | ------- | ----- | ----------------------------- |
| **api1** | `jos3duardo/rinha-backend-2025:v1.0` | 0.3 cores | 67MB | - | API NestJS - Instância 1 |
| **api2** | `jos3duardo/rinha-backend-2025:v1.0` | 0.3 cores | 67MB | - | API NestJS - Instância 2 |
| **api3** | `jos3duardo/rinha-backend-2025:v1.0` | 0.3 cores | 67MB | - | API NestJS - Instância 3 |
| **nginx** | `nginx:latest` | 0.10 cores | 9MB | 9999 | Load Balancer / Reverse Proxy |
| **redis** | `redis:7.2-alpine` | 0.3 cores | 15MB | 6379 | Queue e Cache (BullMQ) |
| **database** | `postgres:17-alpine` | 0.20 cores | 125MB | 5432 | Banco de Dados Principal |
### 📊 Resumo de Recursos
| Métrica | Valor Total |
| --------------------- | -------------------------- |
| **CPU Total** | 1.5 cores |
| **Memória Total** | 350MB |
| **Instâncias da API** | 3 |
| **Redes** | backend, payment-processor |
### 🔧 Configurações Especiais
- **PostgreSQL**: Otimizado para performance com `fsync=0`, `synchronous_commit=0`
- **Redis**: Plataforma linux/amd64 para compatibilidade
- **Nginx**: Load balancer com algoritmo `least_conn`
- **APIs**: Configuradas com restart automático e dependências
### 🌐 Endpoints Expostos
- **API Principal**: `http://localhost:9999` (via Nginx)
- **Redis**: `localhost:6379` (para desenvolvimento)
- **PostgreSQL**: `localhost:5432` (para desenvolvimento)
### Link do desafio
- [Rinha de Backend - 2025](https://github.com/zanfranceschi/rinha-de-backend-2025/
)
-
![img.png](img.png)
![img.png](report/img.png)

View File

@ -1,6 +1,6 @@
services:
api1:
image: payment2:latest
image: jos3duardo/rinha-backend-2025:v1.0
restart: always
networks:
- backend
@ -11,11 +11,11 @@ services:
deploy:
resources:
limits:
cpus: '0.3'
memory: '64MB'
cpus: "0.3"
memory: "67MB"
api2:
image: payment2:latest
image: jos3duardo/rinha-backend-2025:v1.0
restart: always
depends_on:
- redis
@ -26,11 +26,11 @@ services:
deploy:
resources:
limits:
cpus: '0.3'
memory: '64MB'
cpus: "0.3"
memory: "67MB"
api3:
image: payment2:latest
image: jos3duardo/rinha-backend-2025:v1.0
restart: always
depends_on:
- redis
@ -41,14 +41,14 @@ services:
deploy:
resources:
limits:
cpus: '0.3'
memory: '64MB'
cpus: "0.3"
memory: "67MB"
nginx:
image: nginx:latest
restart: always
ports:
- '9999:9999'
- "9999:9999"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
networks:
@ -60,22 +60,22 @@ services:
deploy:
resources:
limits:
cpus: '0.15'
memory: '9MB'
cpus: "0.10"
memory: "9MB"
redis:
image: redis:7.2-alpine
restart: always
platform: linux/amd64
ports:
- '6379:6379'
- "6379:6379"
networks:
- backend
deploy:
resources:
limits:
cpus: '0.40'
memory: '24MB'
cpus: "0.30"
memory: "15MB"
database:
image: postgres:17-alpine
@ -83,15 +83,15 @@ services:
command: postgres -c checkpoint_timeout=600 -c max_wal_size=4096 -c synchronous_commit=0 -c fsync=0 -c full_page_writes=0
platform: linux/amd64
ports:
- '5432:5432'
- "5432:5432"
environment:
- POSTGRES_DB=payment
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=postgres_pwd
volumes:
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
- ./sql/init.sql:/docker-entrypoint-initdb.d/init.sql
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U postgres']
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 3s
timeout: 3s
retries: 5
@ -100,8 +100,8 @@ services:
deploy:
resources:
limits:
cpus: '0.25'
memory: '125MB'
cpus: "0.20"
memory: "125MB"
networks:
backend:

BIN
img.png

Binary file not shown.

Before

Width:  |  Height:  |  Size: 120 KiB

View File

@ -0,0 +1,96 @@
x-service-templates:
payment-processor: &payment-processor
image: zanfranceschi/payment-processor:arm64-20250807221836
networks:
- payment-processor
- payment-processor-db
deploy:
restart_policy:
condition: on-failure
delay: 2s
max_attempts: 10
window: 5s
resources:
limits:
cpus: "1.5"
memory: "100MB"
payment-processor-db: &payment-processor-db
image: postgres:17-alpine
command: postgres -c checkpoint_timeout=600 -c max_wal_size=4096 -c synchronous_commit=0 -c fsync=0 -c full_page_writes=0
networks:
- payment-processor-db
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_USER=postgres
- POSTGRES_DB=rinha
deploy:
restart_policy:
condition: on-failure
delay: 2s
max_attempts: 10
window: 5s
resources:
limits:
cpus: "1.5"
memory: "250MB"
services:
payment-processor-1:
<<: *payment-processor
container_name: payment-processor-default
hostname: payment-processor-default
environment:
- TRANSACTION_FEE=0.05
- RATE_LIMIT_SECONDS=5
- INITIAL_TOKEN=123
- DB_CONNECTION_STRING=Host=/var/run/postgresql;Port=5432;Database=rinha;Username=postgres;Password=postgres;Minimum Pool Size=15;Maximum Pool Size=20;Connection Pruning Interval=3
ports:
- 8001:8080
volumes:
- postgres-socket-01:/var/run/postgresql
depends_on:
- payment-processor-db-1
payment-processor-db-1:
<<: *payment-processor-db
container_name: payment-processor-default-db
hostname: payment-processor-default-db
volumes:
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
- postgres-socket-01:/var/run/postgresql
payment-processor-2:
<<: *payment-processor
container_name: payment-processor-fallback
hostname: payment-processor-fallback
environment:
- TRANSACTION_FEE=0.15
- RATE_LIMIT_SECONDS=5
- INITIAL_TOKEN=123
- DB_CONNECTION_STRING=Host=/var/run/postgresql;Port=5432;Database=rinha;Username=postgres;Password=postgres;Minimum Pool Size=15;Maximum Pool Size=20;Connection Pruning Interval=3
ports:
- 8002:8080
volumes:
- postgres-socket-02:/var/run/postgresql
depends_on:
- payment-processor-db-2
payment-processor-db-2:
<<: *payment-processor-db
container_name: payment-processor-fallback-db
hostname: payment-processor-fallback-db
volumes:
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
- postgres-socket-02:/var/run/postgresql
networks:
payment-processor:
name: payment-processor
driver: bridge
payment-processor-db:
driver: bridge
volumes:
postgres-socket-01:
postgres-socket-02:

View File

@ -0,0 +1,96 @@
x-service-templates:
payment-processor: &payment-processor
image: zanfranceschi/payment-processor:amd64-20250807222453
networks:
- payment-processor
- payment-processor-db
deploy:
restart_policy:
condition: on-failure
delay: 2s
max_attempts: 10
window: 5s
resources:
limits:
cpus: "1.5"
memory: "100MB"
payment-processor-db: &payment-processor-db
image: postgres:17-alpine
command: postgres -c checkpoint_timeout=600 -c max_wal_size=4096 -c synchronous_commit=0 -c fsync=0 -c full_page_writes=0
networks:
- payment-processor-db
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_USER=postgres
- POSTGRES_DB=rinha
deploy:
restart_policy:
condition: on-failure
delay: 2s
max_attempts: 10
window: 5s
resources:
limits:
cpus: "1.5"
memory: "250MB"
services:
payment-processor-1:
<<: *payment-processor
container_name: payment-processor-default
hostname: payment-processor-default
environment:
- TRANSACTION_FEE=0.05
- RATE_LIMIT_SECONDS=5
- INITIAL_TOKEN=123
- DB_CONNECTION_STRING=Host=/var/run/postgresql;Port=5432;Database=rinha;Username=postgres;Password=postgres;Minimum Pool Size=15;Maximum Pool Size=20;Connection Pruning Interval=3
ports:
- 8001:8080
volumes:
- postgres-socket-01:/var/run/postgresql
depends_on:
- payment-processor-db-1
payment-processor-db-1:
<<: *payment-processor-db
container_name: payment-processor-default-db
hostname: payment-processor-default-db
volumes:
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
- postgres-socket-01:/var/run/postgresql
payment-processor-2:
<<: *payment-processor
container_name: payment-processor-fallback
hostname: payment-processor-fallback
environment:
- TRANSACTION_FEE=0.15
- RATE_LIMIT_SECONDS=5
- INITIAL_TOKEN=123
- DB_CONNECTION_STRING=Host=/var/run/postgresql;Port=5432;Database=rinha;Username=postgres;Password=postgres;Minimum Pool Size=15;Maximum Pool Size=20;Connection Pruning Interval=3
ports:
- 8002:8080
volumes:
- postgres-socket-02:/var/run/postgresql
depends_on:
- payment-processor-db-2
payment-processor-db-2:
<<: *payment-processor-db
container_name: payment-processor-fallback-db
hostname: payment-processor-fallback-db
volumes:
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
- postgres-socket-02:/var/run/postgresql
networks:
payment-processor:
name: payment-processor
driver: bridge
payment-processor-db:
driver: bridge
volumes:
postgres-socket-01:
postgres-socket-02:

View File

@ -0,0 +1,8 @@
CREATE UNLOGGED TABLE payments (
correlationId UUID PRIMARY KEY,
amount DECIMAL NOT NULL,
requested_at TIMESTAMP NOT NULL
);
CREATE INDEX payments_requested_at ON payments (requested_at);

BIN
report/img.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 144 KiB

View File

@ -0,0 +1,49 @@
{
"timestamp": "2025-08-18T01:02:58.836Z",
"participante": "anonymous",
"total_liquido": 110893.0485,
"total_bruto": 182244.2,
"total_taxas": 11639.51,
"descricao": "'total_liquido' é sua pontuação final. Equivale ao seu lucro. Fórmula: total_liquido + (total_liquido * p99.bonus) - (total_liquido * multa.porcentagem)",
"p99": {
"valor": "197.38ms",
"bonus": "0%",
"max_requests": 500,
"descricao": "Fórmula para o bônus: max((11 - p99.valor) * 0.02, 0)"
},
"multa": {
"porcentagem": 0.35,
"total": 59711.6415,
"composicao": {
"num_inconsistencias": 6110,
"descricao": "Se 'num_inconsistencias' > 0, há multa de 35%."
}
},
"caixa_dois": {
"detectado": false,
"descricao": "Se 'lag' for negativo, significa que seu backend registrou mais pagamentos do que solicitado, automaticamente desclassificando sua submissão!"
},
"lag": {
"num_pagamentos_total": 9158,
"num_pagamentos_solicitados": 14894,
"lag": 5736,
"descricao": "Lag é a diferença entre a quantidade de solicitações de pagamentos e o que foi realmente computado pelo backend. Mostra a perda de pagamentos possivelmente por estarem enfileirados."
},
"pagamentos_solicitados": {
"qtd_sucesso": 14894,
"qtd_falha": 0,
"descricao": "'qtd_sucesso' foram requests bem sucedidos para 'POST /payments' e 'qtd_falha' os requests com erro."
},
"pagamentos_realizados_default": {
"total_bruto": 156971.2,
"num_pagamentos": 7888,
"total_taxas": 7848.56,
"descricao": "Informações do backend sobre solicitações de pagamento para o Payment Processor Default."
},
"pagamentos_realizados_fallback": {
"total_bruto": 25273,
"num_pagamentos": 1270,
"total_taxas": 3790.95,
"descricao": "Informações do backend sobre solicitações de pagamento para o Payment Processor Fallback."
}
}

44
report/report.html Normal file

File diff suppressed because one or more lines are too long

View File

@ -1124,6 +1124,11 @@
dependencies:
tslib "2.8.1"
"@nestjs/throttler@^6.4.0":
version "6.4.0"
resolved "https://registry.yarnpkg.com/@nestjs/throttler/-/throttler-6.4.0.tgz#5060e2157f4e8b0cb7886eef367751700549de5e"
integrity sha512-osL67i0PUuwU5nqSuJjtUJZMkxAnYB4VldgYUMGzvYRJDCqGRFMWbsbzm/CkUtPLRL30I8T74Xgt/OQxnYokiA==
"@nestjs/typeorm@^11.0.0":
version "11.0.0"
resolved "https://registry.yarnpkg.com/@nestjs/typeorm/-/typeorm-11.0.0.tgz#b0f45d6902396db89e0ac1f4e738c2ff3407b794"