Splitting your FastAPI application and the recalculation worker into separate services within a monorepo is a great approach to enhance scalability, maintainability, and throughput. Below, I'll guide you through organizing your monorepo, structuring the code for reuse, and deploying both services separately on DigitalOcean App Platform.
1. Monorepo Structure
Organizing your project as a monorepo allows both services to share common code while maintaining clear boundaries between them. Here's a suggested directory structure:
your-monorepo/
├── common/
│ ├── __init__.py
│ ├── utils.py
│ ├── models.py
│ └── ... # Other shared modules
├── fastapi_app/
│ ├── app/
│ │ ├── __init__.py
│ │ ├── main.py
│ │ ├── routers/
│ │ └── ... # FastAPI specific modules
│ ├── requirements.txt
│ └── Dockerfile
├── worker/
│ ├── worker/
│ │ ├── __init__.py
│ │ ├── worker.py
│ │ └── ... # Worker specific modules
│ ├── requirements.txt
│ └── Dockerfile
├── tests/
│ ├── ... # Shared tests
├── poetry.lock
├── pyproject.toml
└── README.md
Explanation:
common/: Contains shared code like utility functions, database models, schemas, and any other modules that both services use.
fastapi_app/: Contains the FastAPI application code.
worker/: Contains the recalculation worker code.
tests/: Contains tests that can be shared or separated as needed.
pyproject.toml & poetry.lock: Manage shared dependencies using Poetry (recommended) or you can use other dependency managers like pip with virtual environments.
2. Managing Shared Code
To share the common modules between fastapi_app and worker, you can treat common as an internal Python package. Here's how to set it up:
Using Python Packages
common/__init__.py: Ensure this file exists to make common a Python package.
- Setup Dependencies: Ensure both
fastapi_app and worker have access to the common package. You can achieve this by modifying the PYTHONPATH or by installing the common package as an editable package.
Example with Editable Install (Using Poetry)
Add common as a dependency in both fastapi_app/pyproject.toml and worker/pyproject.toml:
# fastapi_app/pyproject.toml
[tool.poetry.dependencies]
python = "^3.10"
common = { path = "../common" }
fastapi = "^0.95.0"
# ... other dependencies
# worker/pyproject.toml
[tool.poetry.dependencies]
python = "^3.10"
common = { path = "../common" }
pulsar-client = "^2.11.0"
# ... other dependencies
Alternative: Modifying PYTHONPATH
Alternatively, you can adjust the PYTHONPATH in your Dockerfiles or entry scripts to include the common directory.
3. Dependency Management
Using Poetry for managing dependencies keeps things clean and allows for easy sharing of pyproject.toml files.
Setting Up Poetry
-
Initialize Poetry in Monorepo Root:
cd your-monorepo
poetry init
-
Define Workspaces in pyproject.toml:
[tool.poetry]
name = "your-monorepo"
version = "0.1.0"
description = ""
authors = ["Your Name <you@example.com>"]
[tool.poetry.dependencies]
python = "^3.10"
[tool.poetry.dev-dependencies]
pytest = "^7.0"
[tool.poetry.workspace]
packages = ["fastapi_app", "worker", "common"]
-
Install Dependencies:
poetry install
This setup allows each subproject (fastapi_app and worker) to have their own dependencies while sharing the common package.
4. Dockerizing the Services
Containerizing both services ensures consistency across environments and simplifies deployment.
FastAPI Dockerfile
# fastapi_app/Dockerfile
FROM python:3.10-slim
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# Set work directory
WORKDIR /app
# Install dependencies
COPY fastapi_app/pyproject.toml fastapi_app/poetry.lock ./
RUN pip install --upgrade pip
RUN pip install poetry
RUN poetry config virtualenvs.create false
RUN poetry install --no-dev
# Copy application code
COPY fastapi_app/app /app/app
COPY common /app/common
# Expose port
EXPOSE 8000
# Start FastAPI with Uvicorn
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
Worker Dockerfile
# worker/Dockerfile
FROM python:3.10-slim
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# Set work directory
WORKDIR /worker
# Install dependencies
COPY worker/pyproject.toml worker/poetry.lock ./
RUN pip install --upgrade pip
RUN pip install poetry
RUN poetry config virtualenvs.create false
RUN poetry install --no-dev
# Copy worker code
COPY worker/worker /worker/worker
COPY common /worker/common
# Start Worker
CMD ["python", "worker/worker.py"]
Notes:
- Dependencies: Ensure all necessary dependencies are listed in the respective
pyproject.toml.
- Entry Points: Replace
"app.main:app" and "worker/worker.py" with the actual entry points of your FastAPI app and worker script.
5. Setting Up DigitalOcean App Platform
DigitalOcean App Platform allows you to deploy multiple services from a single repository. Here's how to configure it:
Step-by-Step Guide
-
Push Monorepo to Git Repository: Ensure your monorepo is hosted on a platform supported by DigitalOcean (e.g., GitHub, GitLab).
-
Create a New App on DigitalOcean:
- Navigate to the DigitalOcean Control Panel.
- Click on "Apps" and then "Create App".
-
Connect Your Repository:
- Select your repository containing the monorepo.
-
Configure Services:
- FastAPI Service:
- Choose the
fastapi_app directory as the root for this service.
- Select "Docker" as the deployment method.
- Specify the build context (e.g.,
/fastapi_app) and use the fastapi_app/Dockerfile.
- Set environment variables as needed (e.g., database URLs, Pulsar configs).
- Expose port
8000 or whichever port your FastAPI app listens on.
- Worker Service:
- Add a new component for the worker.
- Choose the
worker directory as the root for this service.
- Select "Docker" as the deployment method.
- Specify the build context (e.g.,
/worker) and use the worker/Dockerfile.
- Set environment variables as needed.
- Do not expose any ports unless necessary.
-
Configure Build and Deployment Settings:
- Ensure that each service is built using its respective Dockerfile.
- Configure auto-deployments on push to specific branches if desired.
-
Set Up Environment Variables and Secrets:
- Navigate to each service's settings and add necessary environment variables.
- Use DigitalOcean's secrets management to securely handle sensitive data like API keys, database passwords, and Pulsar credentials.
-
Networking and Scaling:
- Networking: By default, services can communicate over the internal network. Ensure your FastAPI app and worker have the appropriate access to Pulsar and your database.
- Scaling: Set scaling rules based on your application’s needs. The FastAPI app and the worker can scale independently.
-
Monitoring and Logging:
Example Configuration for Services
FastAPI Service
- Build Context:
/fastapi_app
- Dockerfile:
fastapi_app/Dockerfile
- Run Command:
uvicorn app.main:app --host 0.0.0.0 --port 8000
- HTTP Port:
8000
- Environment Variables: Include all necessary variables (e.g.,
DB_URL, PULSAR_URL, etc.)
Worker Service
- Build Context:
/worker
- Dockerfile:
worker/Dockerfile
- Run Command:
python worker/worker.py
- Environment Variables: Include necessary variables for Pulsar, DB access, etc.
6. Development Workflow
Maintain a smooth development workflow by ensuring both services can be developed and tested locally before deploying.
Local Development Setup
-
Use Docker Compose: Create a docker-compose.yml at the monorepo root to orchestrate both services along with dependencies like Apache Pulsar and the database.
version: '3.8'
services:
fastapi:
build:
context: ./fastapi_app
ports:
- "8000:8000"
environment:
- DB_URL=your_db_url
- PULSAR_URL=pulsar://pulsar:6650
depends_on:
- pulsar
worker:
build:
context: ./worker
environment:
- DB_URL=your_db_url
- PULSAR_URL=pulsar://pulsar:6650
depends_on:
- pulsar
pulsar:
image: apachepulsar/pulsar:2.11.0
command: ["bin/pulsar", "standalone"]
ports:
- "6650:6650"
- "8080:8080"
db:
image: postgres:14
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: yourdb
ports:
- "5432:5432"
-
Run Services Locally:
docker-compose up --build
-
Development Tools:
- FastAPI: Utilize
uvicorn with --reload for hot-reloading during development.
- Worker: Implement proper logging and possibly a mechanism to restart on code changes (e.g., using
watchdog or similar tools).
7. Additional Considerations
Separation of Concerns
- Independent Scaling: By separating the FastAPI app and the worker, you can scale them independently based on their specific load and performance characteristics.
- Failure Isolation: Issues in the worker won’t directly impact the FastAPI app and vice versa.
Shared Configuration
- Centralize your configuration management to avoid discrepancies between services. Use environment variables or a configuration service if necessary.
Health Checks
- Implement health check endpoints for both services to ensure they are running correctly and to aid DigitalOcean in managing service health.
Security
- Ensure secure communication between services, especially if they handle sensitive data.
- Use HTTPS for the FastAPI app.
- Secure your Pulsar setup with authentication and authorization if needed.
Continuous Integration/Continuous Deployment (CI/CD)
- Set up CI/CD pipelines to automate testing and deployment. Tools like GitHub Actions, GitLab CI, or DigitalOcean’s built-in CI/CD can be used.
Monitoring and Alerting
- Implement monitoring for both services to track performance metrics, error rates, and system health.
- Set up alerting to notify you of any critical issues.
8. Example Monorepo Configuration
pyproject.toml for common
# common/pyproject.toml
[tool.poetry]
name = "common"
version = "0.1.0"
description = "Shared utilities and models"
authors = ["Your Name <you@example.com>"]
[tool.poetry.dependencies]
python = "^3.10"
# Add other shared dependencies
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
pyproject.toml for fastapi_app
# fastapi_app/pyproject.toml
[tool.poetry]
name = "fastapi_app"
version = "0.1.0"
description = "FastAPI application"
authors = ["Your Name <you@example.com>"]
[tool.poetry.dependencies]
python = "^3.10"
fastapi = "^0.95.0"
uvicorn = "^0.22.0"
common = { path = "../common" }
# Add other dependencies
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
pyproject.toml for worker
# worker/pyproject.toml
[tool.poetry]
name = "worker"
version = "0.1.0"
description = "Recalculation worker"
authors = ["Your Name <you@example.com>"]
[tool.poetry.dependencies]
python = "^3.10"
pulsar-client = "^2.11.0"
common = { path = "../common" }
# Add other dependencies
[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"
9. Summary
By organizing your project as a monorepo with clearly separated FastAPI and worker services, leveraging shared code through a common package, and containerizing both services, you set up a scalable and maintainable architecture. Deploying them as separate services on DigitalOcean App Platform allows each to scale independently and ensures robust performance. Here's a quick checklist to get started:
- Monorepo Structure: Organize your code with
common, fastapi_app, and worker directories.
- Shared Code: Use Python packages to share code between services.
- Dependency Management: Use Poetry to manage dependencies for each service.
- Containerization: Create separate Dockerfiles for FastAPI and worker services.
- Deployment: Deploy both services separately on DigitalOcean App Platform, configuring each with appropriate build contexts and environment variables.
- Development Workflow: Use Docker Compose for local development, ensuring parity with production environments.
- Monitoring and Scaling: Implement monitoring, health checks, and set up appropriate scaling rules.
Feel free to ask if you need more detailed guidance on any of these steps!