Separating your FastAPI application and the recalculation worker into distinct services can indeed improve scalability, maintainability, and throughput. Here’s a comprehensive approach to organizing your monorepo and deploying the separated services effectively on DigitalOcean App Platform.
1. Monorepo Structure
A monorepo enables you to manage multiple related projects within a single repository, facilitating code reuse and easier dependency management. Here’s a suggested structure:
/your-monorepo
├── /common
│ ├── __init__.py
│ ├── models.py
│ ├── utils.py
│ └── ... # Any shared modules
├── /fastapi_app
│ ├── main.py
│ ├── routers/
│ ├── dependencies.py
│ └── ... # FastAPI-specific code
├── /worker
│ ├── worker.py
│ └── ... # Worker-specific code
├── /configs
│ ├── fastapi_config.yaml
│ └── worker_config.yaml
├── docker-compose.yml
├── requirements.txt
└── README.md
Explanation:
-
/common: Contains shared code such as data models, utility functions, and any other modules both services use. This prevents duplication and ensures consistency.
-
/fastapi_app: Contains all FastAPI-specific code, including routers, dependencies, and the main application entry point.
-
/worker: Houses the worker logic that handles recalculations, interacts with Pulsar, and updates the database.
-
/configs: Configuration files for different services, enabling environment-specific settings.
-
Root Files:
docker-compose.yml: Facilitates local development by allowing you to run both services together.
requirements.txt: Lists all Python dependencies, including those for both services.
README.md: Documentation for the repository.
2. Code Sharing and Reusability
To maximize code reuse between the FastAPI app and the worker:
-
Shared Libraries: Place all shared logic in the /common directory. Both fastapi_app and worker can import from common as needed.
# Example: fastapi_app/main.py
from common.utils import some_shared_function
# Example: worker/worker.py
from common.utils import some_shared_function
-
Dependency Management: Ensure that your requirements.txt includes all dependencies required by both services. Alternatively, you can have separate requirements.txt files within each service if they have significantly different dependencies.
3. Containerization
Containerizing both services ensures consistency across environments and simplifies deployment. Here’s how you can approach it:
Docker Setup
Dockerfile for FastAPI App (fastapi_app/Dockerfile):
FROM python:3.11-slim
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY ./fastapi_app /app/fastapi_app
COPY ./common /app/common
# Command to run FastAPI
CMD ["uvicorn", "fastapi_app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Dockerfile for Worker (worker/Dockerfile):
FROM python:3.11-slim
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy worker code
COPY ./worker /app/worker
COPY ./common /app/common
# Command to run the worker
CMD ["python", "worker/worker.py"]
docker-compose.yml
For local development, you can use docker-compose to run both services:
version: '3.8'
services:
fastapi_app:
build:
context: .
dockerfile: fastapi_app/Dockerfile
ports:
- "8000:8000"
environment:
- PULSAR_BROKER_URL=pulsar://pulsar:6650
# Add other environment variables
depends_on:
- pulsar
worker:
build:
context: .
dockerfile: worker/Dockerfile
environment:
- PULSAR_BROKER_URL=pulsar://pulsar:6650
# Add other environment variables
depends_on:
- pulsar
pulsar:
image: apachepulsar/pulsar:latest
command: ["bin/pulsar", "standalone"]
ports:
- "6650:6650"
- "8080:8080"
4. Deployment on DigitalOcean App Platform
DigitalOcean App Platform allows you to deploy multiple services from a single repository. Here’s how to set it up:
Separate Components as Services
After separating your application into fastapi_app and worker, you can deploy them as separate components on the App Platform:
-
FastAPI Service:
- Source: Point to the
fastapi_app directory.
- Build Command: If using Docker, specify the path to the
fastapi_app/Dockerfile.
- Run Command: The
CMD in your Dockerfile handles this.
- Environment Variables: Set necessary variables, such as
PULSAR_BROKER_URL, database credentials, etc.
-
Worker Service:
- Source: Point to the
worker directory.
- Build Command: Specify the path to the
worker/Dockerfile.
- Run Command: The
CMD in your Dockerfile handles this.
- Environment Variables: Similar to the FastAPI service.
Setting Up Dependencies
Ensure that both services can communicate with Apache Pulsar. If Pulsar is managed externally (e.g., using a managed Pulsar service or deploying Pulsar separately on DigitalOcean), configure both services with the correct PULSAR_BROKER_URL.
Using Environment Variables
Handle environment-specific configurations using environment variables. DigitalOcean allows you to set these variables in the App Platform dashboard, keeping configurations secure and manageable.
Scaling Considerations
With separate services, you can scale them independently based on load:
- FastAPI App: Scale horizontally to handle more incoming HTTP/WebSocket requests.
- Worker: Scale based on the number of messages in the Pulsar queue or the computation load.
5. CI/CD Pipeline
Implement a CI/CD pipeline to automate building and deploying your services. Tools like GitHub Actions, GitLab CI, or DigitalOcean’s built-in CI/CD can help:
-
Build Phase:
- Lint and test your code.
- Build Docker images for both
fastapi_app and worker.
-
Deploy Phase:
- Push Docker images to a container registry (DigitalOcean Container Registry or Docker Hub).
- Deploy the latest images to the App Platform.
6. Logging and Monitoring
Ensure visibility into both services:
-
Logging: Use centralized logging solutions like DigitalOcean’s built-in logging, ELK stack, or other log aggregators to collect logs from both services.
-
Monitoring: Implement monitoring for health checks, performance metrics, and alerting. DigitalOcean App Platform provides some monitoring tools, but you might also integrate with external services like Prometheus, Grafana, or Datadog.
7. Handling Dependencies and Updates
To maintain code consistency and manage dependencies:
-
Python Packages: If your /common codebase grows significantly, consider packaging it as an internal Python package and managing it via a private PyPI repository or as a Git submodule.
-
Version Control: Use version control branches effectively. For example, ensure that updates to /common are compatible with both services before merging.
8. Security Considerations
-
Secrets Management: Use DigitalOcean’s secrets management to handle sensitive information like API keys, database credentials, and Pulsar authentication tokens.
-
Network Security: Ensure that your services communicate securely with Pulsar, possibly through TLS if supported.
9. Potential Enhancements
-
Service Discovery: If you have multiple worker instances, use service discovery mechanisms to balance load.
-
Retry Mechanisms: Implement retry logic and dead-letter queues in your worker to handle failed message processing gracefully.
-
Graceful Shutdown: Ensure that both services handle shutdown signals gracefully, allowing in-flight processes to complete and resources to be cleaned up properly.
10. Example Workflow
Here’s an example flow after separation:
-
User Interaction: A user clicks "claim points" on the frontend, sending a request to the FastAPI service via HTTP.
-
FastAPI Processing:
- Validates the request.
- Publishes a message to Pulsar with necessary data for recalculation.
-
Worker Processing:
- Subscribes to the relevant Pulsar topic.
- Receives the message, performs recalculations, and updates the database.
- Publishes an update message to another Pulsar topic with the new points data.
-
FastAPI WebSocket:
- Subscribes to the Pulsar topic for updates.
- Upon receiving an update message, pushes the updated data to the user via WebSocket.
11. Final Tips
-
Documentation: Document your monorepo structure, deployment steps, and any scripts you create. This aids onboarding and future maintenance.
-
Testing: Implement comprehensive testing for both services, including unit tests, integration tests, and end-to-end tests to ensure reliability after separation.
-
Incremental Migration: If separating the services introduces complexity, consider incrementally decoupling parts of the worker from the FastAPI app, gradually moving towards full separation.
By following this structured approach, you can effectively separate your FastAPI application and the recalculation worker into distinct, scalable, and maintainable services within a monorepo, all while leveraging the capabilities of DigitalOcean App Platform.