Microservices Architecture
ποΈ System Architecture
GitiNext backend is built as a collection of independent microservices, each responsible for a specific domain.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Client Layer β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Telegram Bot β Telegram Mini App (TMA) β Admin Panel β TWA β
ββββββββββ¬ββββββββββββββββββββ¬ββββββββββββββββββββββ¬βββββββββββ¬βββββββββ
β β β β
β Bot API β HTTPS/REST β HTTPS β HTTPS
βΌ βΌ βΌ βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β GATEWAY SERVICE β
β βββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
β β HTTP/REST β β WebSocket β β gRPC Gateway β β
β β :8080 β β :8082 β β :8081 β β
β βββββββββββββββ ββββββββββββββββ ββββββββββββββββ β
ββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββββββ¬βββββββββββ
β β
β Internal gRPC Network β
β β
ββββββ΄βββββββββββββββ¬βββββββββββββββββ¬βββββββββββββββββββ΄βββββ
β β β β
βΌ βΌ βΌ βΌ
βββββββββββ βββββββββββ βββββββββββ ββββββββββββ
β WALLET β β WATCHER β β ACCOUNT β β MARKET β
β :9092 β β :9093 β β :9091 β β :9094 β
ββββββ¬βββββ ββββββ¬βββββ ββββββ¬βββββ ββββββ¬ββββββ
β β β β
βΌ βΌ βΌ βΌ
βββββββββββ βββββββββββ βββββββββββ ββββββββββββ
βTRANSACT β β PAYMENT β β VOUCHER β β SUPPORT β
β :9095 β β :9096 β β :9097 β β :9098 β
βββββββββββ βββββββββββ βββββββββββ ββββββββββββ
β β β β
ββββββββββββββββββ΄ββββββββββββββββ΄ββββββββββββββββββββββββ
β
βΌ
ββββββββββββββββββββββββββββββββββββββββββββββββ
β Shared Infrastructure β
ββββββββββββββββββββββββββββββββββββββββββββββββ€
β PostgreSQL β Redis β MinIO β NATS β Traefik β
ββββββββββββββββββββββββββββββββββββββββββββββββ
π¦ Service Catalog
Core Services
1. Gateway Service (:8080, :8081, :8082)
Purpose: HTTP/REST entry point and gRPC gateway
Responsibilities:
- Route HTTP requests to gRPC services
- JWT authentication
- Rate limiting
- CORS handling
- WebSocket connections
- Request/response logging
- Error mapping (gRPC β HTTP status codes)
Tech Stack:
- Native Go HTTP server
- gRPC client connections
- WebSocket (gorilla/websocket)
Endpoints:
http://gateway:8080- Public REST APIhttp://gateway:8081- Admin REST APIws://gateway:8082- WebSocket
2. Wallet Service (:9092)
Purpose: Cryptocurrency wallet management
Responsibilities:
- HD wallet generation (TON, TRON, ETH, BSC)
- Address derivation (BIP39/44)
- Transaction signing
- Balance queries
- Deposit address management
- Withdrawal processing
- WalletConnect integration
Tech Stack:
- tonutils-go (TON)
- gotron-sdk (TRON)
- go-ethereum (ETH/BSC)
- Trust Wallet Core (optional, via CGO)
Database Tables:
wallets- Wallet instanceswallet_roots- HD wallet master keyswallet_connections- WalletConnect sessions
gRPC Interface:
CreateWallet()GetWallet()ListWallets()SetDefaultWallet()GetDepositAddress()SignTransaction()
3. Watcher Service (Multiple Instances)
Purpose: Blockchain monitoring and deposit detection
Responsibilities:
- Poll blockchain nodes for new blocks
- Parse transactions
- Detect deposits to monitored addresses
- Track confirmations
- Emit deposit events to outbox
- Handle blockchain reorgs
Instances:
watcher-ton- TON blockchainwatcher-tron- TRON blockchain (TRC20 tokens)watcher-bsc- Binance Smart Chain (future)watcher-eth- Ethereum (future)
Tech Stack:
- TON RPC client
- TronGrid API client
- Cursor-based polling
- Idempotency keys
Database Tables:
chain_cursors- Last processed block per chaindeposits- Detected depositsoutbox- Events for downstream processing
No gRPC Interface: Background workers only
4. Account Service (:9091)
Purpose: User account and authentication management
Responsibilities:
- User CRUD operations
- Telegram authentication validation
- User settings and preferences
- Identity verification (KYC)
- Account recovery
- Level-up system
- Admin user management
Database Tables:
users- User accountsadmins- Admin usersroles- User rolesclaims- Permissionsbusinesses- Business accounts
gRPC Interface:
CreateUser()GetUser()UpdateUser()VerifyTelegramAuth()GetUserProfile()
5. Market Service (:9094) TO BE CREATED
Purpose: Cryptocurrency market data and prices
Responsibilities:
- Fetch prices from CoinGecko/CoinMarketCap
- Aggregate price data
- Generate chart data (OHLC)
- Calculate Toman prices (via Nobitex)
- Cache prices in Redis (1-minute TTL)
- Broadcast price updates via WebSocket
Database Tables:
assets- Supported cryptocurrenciesasset_prices- Historical pricesexchange_rates- Fiat exchange rates
gRPC Interface:
GetAssets()GetAsset(symbol)GetPrices(symbols[])GetChartData(symbol, timeframe)
6. Transaction Service (:9095) TO BE CREATED
Purpose: Transaction history and trading operations
Responsibilities:
- Transaction history (paginated)
- Buy cryptocurrency orders
- Sell cryptocurrency orders
- Swap operations (atomic)
- Fee calculation
- Balance locking
- Order processing pipeline
- Event emission
Database Tables:
transactions- All transactionsorders- Pending ordersledger_entries- Double-entry accountinguser_balances- Aggregated balances
gRPC Interface:
GetTransactions(userId, pagination)GetTransaction(id)CreateBuyOrder()CreateSellOrder()CreateSwapOrder()CalculateFees()
7. Payment Service (:9096) TO BE CREATED
Purpose: payment gateway integration
Responsibilities:
- Paystar integration (deposits/withdrawals)
- FinnoTech integration (banking API)
- Card-to-card processing
- IBAN deposit handling
- Automated transaction detection
- Withdrawal approval workflow
External APIs:
- Paystar API
- FinnoTech API (with proxy support)
Database Tables:
user_cards- Bank cardscard_transactions- Card depositswithdrawals- Withdrawal requestspayment_transactions- Payment records
gRPC Interface:
CreateDeposit()CreateWithdrawal()GetWithdrawalLimits()ApproveWithdrawal()
8. Voucher Service (:9097) TO BE CREATED
Purpose: Voucher purchase and redemption
Responsibilities:
- PS Voucher integration (gaming)
- HOT Voucher integration
- UTOPIA Voucher integration (UUSD)
- Voucher rate management
- Buy/sell/redeem operations
- Transaction history per voucher type
External APIs:
- PS Voucher API
- HOT Voucher API
- UTOPIA API
Database Tables:
vouchers- Voucher recordsvoucher_rates- Exchange ratesvoucher_transactions- Purchase/sale history
gRPC Interface:
BuyVoucher(type, amount)SellVoucher(code)RedeemVoucher(code)GetVoucherRates()ValidateVoucher(code)
9. Blockchain Service (:9098) TO BE CREATED
Purpose: Exonyx blockchain API integration
Responsibilities:
- Exonyx API client (reseller endpoints)
- Wallet balance monitoring
- Transaction broadcasting
- Webhook handling
- Hot wallet management
External APIs:
- Exonyx API (api.exonyxco.com)
Database Tables:
blockchain_transactions- On-chain transactionshot_wallets- System hot walletscold_wallets- Cold storage addresses
gRPC Interface:
GetBlockchainBalance()BroadcastTransaction()GetTransactionStatus()
10. Support Service (:9099) TO BE CREATED
Purpose: Customer support ticket system
Responsibilities:
- Ticket CRUD operations
- Message threading
- File attachments (via MinIO)
- Admin notifications (via Telegram)
- Ticket assignment
- Status tracking
Database Tables:
tickets- Support ticketsticket_messages- Message threadsticket_attachments- File uploads
gRPC Interface:
CreateTicket()GetTickets(userId)GetTicket(id)AddMessage(ticketId, message)CloseTicket(id)
11. KYC Service (:9100) TO BE CREATED
Purpose: Identity verification and KYC workflows
Responsibilities:
- Document upload (ID cards, selfies)
- Phone verification (SMS)
- Admin review workflow
- Approval/rejection
- Status tracking
- Integration with SMS providers
Database Tables:
kyc_submissions- KYC documentsverification_codes- Phone/email codesverification_requests- Verification requests
gRPC Interface:
SubmitKYC()GetKYCStatus()SendPhoneCode()VerifyPhoneCode()ApproveKYC()(admin)RejectKYC()(admin)
π Service Communication
Internal (gRPC):
Gateway β Wallet gRPC β Wallet Service
Gateway β Account gRPC β Account Service
Watcher β Database β (No gRPC, writes directly)
Event-Driven (NATS/Outbox):
Watcher β Outbox Table β NATS β Accounting Service
Transaction β Outbox Table β NATS β Notification Service
External APIs:
Market Service β CoinGecko/CMC API
Payment Service β Paystar/FinnoTech API
Voucher Service β PS/HOT/UTOPIA APIs
Blockchain Service β Exonyx API
π Service Dependencies
graph TD
Gateway[Gateway Service]
Wallet[Wallet Service]
Watcher[Watcher Service]
Account[Account Service]
Market[Market Service]
Transaction[Transaction Service]
Payment[Payment Service]
Gateway --> Wallet
Gateway --> Account
Gateway --> Market
Gateway --> Transaction
Gateway --> Payment
Watcher --> PostgreSQL
Wallet --> PostgreSQL
Account --> PostgreSQL
Transaction --> PostgreSQL
Market --> Redis
Transaction --> Redis
Wallet --> Redis
All --> NATS[NATS Messaging]
π― Design Principles
1. Independence
Each service can be:
- Developed independently
- Deployed independently
- Scaled independently
- Tested independently
2. Single Responsibility
- Each service has ONE domain
- No business logic in gateway
- Repositories handle DB only
- Services handle business logic
3. Event-Driven
- Use outbox pattern for external effects
- NATS for async communication
- Events are idempotent
4. Resilience
- Circuit breakers for external APIs
- Retry with exponential backoff
- Graceful degradation
- No cascading failures
5. Observability
- Prometheus metrics on all services
- OpenTelemetry tracing
- Structured logging (zap)
- Health check endpoints
π Security Architecture
Authentication:
- Telegram
initDatavalidation (HMAC-SHA256) - JWT tokens for session management
- Internal service tokens for gRPC
Authorization:
- Role-based access control (RBAC)
- Permission claims
- Admin vs user separation
Data Security:
- Mnemonic encryption (AES-256-GCM)
- Private keys never stored
- TLS for all communication
- Secrets in environment variables
π Scalability
Horizontal Scaling:
- Stateless services (scale by adding instances)
- Sticky sessions for WebSocket
- Database connection pooling
- Redis for distributed locking
Vertical Scaling:
- Configurable worker pools
- Bounded concurrency
- Memory limits
- CPU limits
Caching Strategy:
- Redis for hot data (balances, prices)
- TTL-based expiration
- Cache invalidation on updates
- Write-through for critical data
π Service Lifecycle
Startup:
- Load configuration
- Initialize database connection
- Run migrations (if needed)
- Initialize Redis connection
- Initialize gRPC server
- Register health checks
- Start HTTP server (if applicable)
- Ready to serve
Shutdown (Graceful):
- Stop accepting new requests
- Finish processing current requests
- Drain queues
- Close database connections
- Close Redis connections
- Exit
Health Checks:
GET /health β 200 OK
{
"status": "healthy",
"service": "wallet",
"version": "1.0.0",
"uptime": "3h25m",
"dependencies": {
"database": "healthy",
"redis": "healthy",
"nats": "healthy"
}
}
π Monitoring & Metrics
Prometheus Metrics (per service):
# Request metrics
http_requests_total{method, path, status}
http_request_duration_seconds{method, path}
# gRPC metrics
grpc_server_handled_total{service, method, code}
grpc_server_handling_seconds{service, method}
# Database metrics
db_connections_active
db_connections_idle
db_query_duration_seconds{query_type}
# Business metrics
wallets_created_total{network}
deposits_detected_total{network}
withdrawals_processed_total{network, status}
balance_queries_total{network}
Logs (Structured JSON):
{
"level": "info",
"ts": "2025-10-06T10:30:00Z",
"service": "wallet",
"msg": "Wallet created",
"telegram_id": 123456789,
"network": "TON",
"address": "EQ...",
"duration_ms": 45
}
π Deployment
Development:
docker-compose up -d
Production (Docker Swarm):
docker stack deploy -c docker-compose.yaml gitinext
Individual Service:
docker build -t wallet:latest services/wallet
docker run -p 9092:9092 --env-file .env wallet:latest
π Next Steps
- Database Schema - Understand data model
- Security Architecture - Security details
- External Integrations - Third-party APIs
- Service Guides - Service-specific documentation