Skip to content

About

Learning ballerina for bring up skill

Resources

Contributing

Security policy

Stars

0 stars

Watchers

1 watching

Forks

Latest commit

Β 

History

21 Commits

Folders and files

Repository files navigation

Ballerina Study - Production-Ready Microservices

A comprehensive Ballerina application showcasing production-ready features and best practices for building cloud-native microservices.

πŸš€ Overview

This repository demonstrates enterprise-grade Ballerina applications with:

  • RESTful APIs with proper error handling
  • Database integration with ACID transactions
  • Concurrent processing with Ballerina workers
  • Health checks and observability
  • Containerization and cloud deployment
  • Security best practices
  • Comprehensive testing

πŸ“‹ Table of Contents

✨ Features

Production-Ready Components

  • βœ… RESTful API Server - Full CRUD operations with validation
  • βœ… Database Service - Transaction management and data integrity
  • βœ… Game Server - AI-integrated game backend with player management
  • βœ… AWS Lambda Function - Serverless deployment example
  • βœ… DAG Implementation - Advanced data structure with algorithms

Ballerina Features Demonstrated

  • πŸ”„ Concurrent Processing - Worker-based parallelism
  • πŸ”’ Transaction Management - ACID compliance with rollback support
  • πŸ“Š Observability - Metrics, logging, and tracing
  • πŸ›‘οΈ Error Handling - Structured error responses
  • βš™οΈ Configuration Management - Environment-based config
  • 🐳 Containerization - Docker and Docker Compose support
  • ☸️ Cloud Native - Kubernetes deployment ready
  • πŸ§ͺ Testing - Comprehensive test suite
  • πŸ”Œ GraphQL - Modern API with subscriptions
  • πŸ”— WebSocket - Real-time bidirectional communication
  • 🌐 gRPC - High-performance RPC framework (proto definitions included)

πŸ—οΈ Architecture

ballerina-study/
β”œβ”€β”€ main.bal                    # Main production server (Port 9090)
β”œβ”€β”€ database_service.bal        # Database/transaction service (Port 9091)
β”œβ”€β”€ graphql_service.bal         # GraphQL API service (Port 4000)
β”œβ”€β”€ websocket_service.bal       # WebSocket chat service (Port 9092)
β”œβ”€β”€ src/main/server/
β”‚   β”œβ”€β”€ server_ai.bal          # Game server with AI (Port 8080)
β”‚   └── aws/
β”‚       β”œβ”€β”€ lambda/ballerina.bal   # AWS Lambda function
β”‚       └── dag/dag.bal            # DAG implementation
β”œβ”€β”€ tests/                      # Test files
β”œβ”€β”€ proto/                      # gRPC protocol definitions
β”œβ”€β”€ k8s/                        # Kubernetes manifests
β”œβ”€β”€ .github/workflows/          # CI/CD pipelines
β”œβ”€β”€ Ballerina.toml             # Package configuration
β”œβ”€β”€ Cloud.toml                 # Cloud deployment config
β”œβ”€β”€ Dockerfile                 # Container image
β”œβ”€β”€ docker-compose.yml         # Multi-service orchestration
β”œβ”€β”€ DEPLOYMENT.md              # Production deployment guide
β”œβ”€β”€ OBSERVABILITY.md           # Monitoring and observability
β”œβ”€β”€ SECURITY.md                # Security best practices
└── CONTRIBUTING.md            # Contributing guidelines

🚦 Getting Started

Prerequisites

  • Ballerina 2201.8.0 or later (Download)
  • Java 11 or later
  • Docker (optional, for containerized deployment)

Quick Start

  1. Clone the repository:
git clone https://github.com/smaruf/ballerina-study.git
cd ballerina-study
  1. Run the main production server:
bal run main.bal
  1. Test the health endpoint:
curl http://localhost:9090/api/v1/health
  1. Create a user:
curl -X POST http://localhost:9090/api/v1/users \
  -H "Content-Type: application/json" \
  -d '{"name":"John Doe","email":"john@example.com"}'

πŸ”§ Services

1. Production Server (main.bal)

Port: 9090

A comprehensive REST API demonstrating production-ready patterns:

  • Health & Readiness: /api/v1/health, /api/v1/ready
  • User Management: CRUD operations with validation
  • Metrics: /api/v1/metrics
  • Concurrent Processing: Worker-based parallel execution
  • Transactions: Atomic operations with rollback

2. Database Service (database_service.bal)

Port: 9091

E-commerce backend with transaction management:

  • Product Management: Create, read, update products
  • Order Processing: Transaction-safe order creation
  • Stock Management: Automatic inventory updates
  • Order Lifecycle: Status updates and cancellations

3. Game Server (server_ai.bal)

Port: 8080

AI-integrated game backend:

  • Player Management: Join, track actions and reactions
  • AI Integration: Multiple AI provider fallback logic
  • RAG Models: Create and store RAG models
  • Real-time State: In-memory game state management

4. GraphQL Service (graphql_service.bal)

Port: 4000

GraphQL API for book management:

  • Queries: Get books, search, filter
  • Mutations: Create, update, delete books
  • Subscriptions: Real-time updates
  • GraphiQL: Interactive GraphQL playground at /graphiql

5. WebSocket Service (websocket_service.bal)

Port: 9092

Real-time chat application:

  • Real-time Messaging: Instant message delivery
  • Typing Indicators: Show when users are typing
  • User Presence: Track online users
  • Chat History: Maintain message history
  • Connection: ws://localhost:9092/chat

6. AWS Lambda Function (ballerina.bal)

Port: 8080

Serverless function example:

  • Lambda Handler: AWS-compatible request/response
  • Async Processing: Background task execution
  • Health Checks: Container health monitoring

7. DAG Service (dag.bal)

Standalone directed acyclic graph implementation:

  • Graph Operations: Add nodes and edges
  • Cycle Detection: DFS-based cycle detection
  • Topological Sort: Dependency ordering
  • Visualization: Console-based graph printing

βš™οΈ Configuration

Environment Variables

# Main Production Server
export serverPort=9090
export environment=production
export enableMetrics=true
export requestTimeout=30000

# Game Server
export gameServerPort=8080

# Database Service
export dbHost=localhost
export dbPort=3306
export dbName=ballerina_store

# Lambda Function
export lambdaPort=8080

Configuration File (Config.toml)

[ballerina_study.production_server]
serverPort = 9090
environment = "production"
enableMetrics = true
requestTimeout = 30000

See DEPLOYMENT.md for complete configuration options.

πŸ’» Development

Build the Project

bal build

Run Individual Services

# Production server
bal run main.bal

# Database service
bal run database_service.bal

# GraphQL service
bal run graphql_service.bal
# Then visit: http://localhost:4000/graphiql

# WebSocket chat service
bal run websocket_service.bal
# Connect using: ws://localhost:9092/chat

# Game server
cd src/main/server
bal run server_ai.bal

# DAG standalone
cd src/main/server/aws/dag
bal run dag.bal

Code Quality

# Format code
bal format

# Run linter (if available)
bal lint

πŸ§ͺ Testing

Run All Tests

bal test

Run Specific Test File

bal test tests/main_test.bal
bal test tests/database_test.bal

Test Coverage

Tests cover:

  • βœ… Health and readiness endpoints
  • βœ… User CRUD operations
  • βœ… Input validation
  • βœ… Error handling
  • βœ… Product and order management
  • βœ… Transaction rollback scenarios
  • βœ… Concurrent processing

🐳 Deployment

Docker Deployment

# Build image
docker build -t ballerina-study:1.0.0 .

# Run with Docker Compose
docker-compose up -d

# Check status
docker-compose ps

# View logs
docker-compose logs -f

Kubernetes Deployment

# Generate K8s artifacts
bal build --cloud=k8s

# Deploy to cluster
kubectl apply -f target/kubernetes/production_server/

# Check deployment
kubectl get pods
kubectl get services

AWS Lambda Deployment

See DEPLOYMENT.md for detailed Lambda deployment instructions.

πŸ“š API Documentation

Main Production Server API

Health Check

GET /api/v1/health

Response:

{
  "status": "UP",
  "environment": "production",
  "timestamp": "2024-01-26T05:30:00Z",
  "version": "1.0.0"
}

Create User

POST /api/v1/users
Content-Type: application/json

{
  "name": "John Doe",
  "email": "john@example.com"
}

Response (201 Created):

{
  "success": true,
  "message": "User created successfully",
  "data": {
    "id": "uuid-here",
    "name": "John Doe",
    "email": "john@example.com",
    "createdAt": "2024-01-26T05:30:00Z"
  }
}

Get User

GET /api/v1/users/{id}

List Users (with pagination)

GET /api/v1/users?limit=10&offset=0

Update User

PUT /api/v1/users/{id}
Content-Type: application/json

{
  "name": "Jane Doe",
  "email": "jane@example.com"
}

Delete User

DELETE /api/v1/users/{id}

Concurrent Processing

POST /api/v1/process/concurrent
Content-Type: application/json

{
  "data": "test data"
}

Database Service API

Create Product

POST /store/products
Content-Type: application/json

{
  "name": "Product Name",
  "price": 99.99,
  "quantity": 100
}

Create Order (with transaction)

POST /store/orders
Content-Type: application/json

{
  "userId": "user-id",
  "productId": "product-id",
  "quantity": 2
}

Cancel Order (with stock restoration)

POST /store/orders/{id}/cancel

See full API documentation in DEPLOYMENT.md.

🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

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

πŸ“– Resources

Ballerina Documentation

Best Practices

Community

πŸ“ License

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

πŸ™ Acknowledgments

  • Ballerina team for the excellent language and documentation
  • Community contributors and examples
  • Cloud native computing foundation for best practices

Built with ❀️ using Ballerina

About

Learning ballerina for bring up skill

Resources

Contributing

Security policy

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages